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 would the background be transparent, but any white part of the image.
If you find it valid to apply the following script to your code (instead of using a graphical application to remove the background of your icon in question), follow it:
HTML:
The image and the canvas
should 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 in browsers with HTML5 support (more browsers
modern).
I think the only way to do that is just by putting an image that has a transparent background. I may be wrong.
– Leandro Lima