There is a way to make a specific color of an image transparent using canvas
. In your case, the image has a white background, so with canvas
, not only the background would be transparent, but any white part of the image.
If you find it valid to apply the script below in your code (instead of using a graphics application to remove the background of your icon in question), follow it:
HTML:
The image and canvas
must be in the same div
:
<div>
<img id="fundobranco" src="imagem.png" style="display: none;">
<canvas id="semfundobranco"></canvas>
</div>
Script:
<script>
window.onload = function(){
id_imagem = "fundobranco"; // id da imagem
largura_imagem = 400; // width da imagem
altura_imagem = 400; // height da imagem
var canvas = document.getElementById("semfundobranco"),
ctx = canvas.getContext("2d"),
image = document.getElementById(id_imagem);
canvas.height = altura_imagem; canvas.width = largura_imagem;
ctx.drawImage(image,0,0);
var imgd = ctx.getImageData(0, 0, largura_imagem, altura_imagem),
pix = imgd.data,
newColor = {r:0,g:0,b:0, a:0};
for(var i = 0, n = pix.length; i <n; i += 4){
var r = pix[i],
g = pix[i+1],
b = pix[i+2];
if(r== 255 && g == 255 && b == 255){
pix[i] = newColor.r;
pix[i+1] = newColor.g;
pix[i+2] = newColor.b;
pix[i+3] = newColor.a;
}
}
ctx.putImageData(imgd, 0, 0);
}
</script>
Notes:
The image must be in the same domain.
Only works with browsers with HTML5 support (older browsers
modern).