I am trying to draw an image over another image in a canvas, and in the first image I am trying to remove the white pixels and make them transparent, but they are turning black.
This is the code I am using, but it’s not looking correct. Does anyone see the problem?
function draw_graphic(canvas,context,lgo_type,gph_img,rib_type, hl_col,hl_txt,cp_col,cp_txt,in_col,in_txt,img_src,ban_bor) {
// add the graphic image
if (gph_img!="") {
var img3 = new Image();
img3.src = gph_img;
img3.onload = function() {
/*/////////////////////////////////////////*/
var img6 = new Image();
img6.src = remove_all_pixels(img3, 255, 255, 255);
img6.onload = function() {
/*/////////////////////////////////////////*/
context.globalCompositeOperation = 'destination-out';
if (rib_type=="1" || rib_type=="3" || rib_type=="5") {
context.drawImage(this,0,0,143,105);
} else {
context.drawImage(this,465,0,143,105);
}
context.globalCompositeOperation = 'source-over';
draw_logo(canvas,context,lgo_type,rib_type, hl_col,hl_txt,cp_col,cp_txt,in_col,in_txt,img_src,ban_bor);
}
};
} else {
draw_logo(canvas,context,lgo_type,rib_type, hl_col,hl_txt,cp_col,cp_txt,in_col,in_txt,img_src,ban_bor);
}
}
function remove_all_pixels(image, r_val, g_val, b_val) {
var canvas2 = document.createElement('canvas');
var ctx = canvas2.getContext("2d");
canvas2.width = image.width;
canvas2.height = image.height;
ctx.drawImage(image,0,0);
var imgd = ctx.getImageData(0, 0, canvas2.width, canvas2.height);
var pix = imgd.data;
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 == r_val && g == g_val && b == b_val){
pix[i] = 0;
pix[i+1] = 0;
pix[i+2] = 0;
pix[i+2] = 0;
}
}
ctx.putImageData(imgd, 0, 0);
return canvas2.toDataURL();
}
You need to change the offset of the last value from 2 to 3. Since
pix[i+3]controls the alpha channel.Sorry that was my fault from your last question. Was a typo in my code I provided in the answer, however the fiddle worked perfectly.
http://jsfiddle.net/loktar/BtbSM/