javascript - 如何在 IE9 中不是黑色的 html5 Canvas 中创建透明像素

标签 javascript html canvas

我试图在 Canvas 中的另一幅图像上绘制一幅图像,在第一幅图像中,我试图移除白色像素并使它们透明,但它们正在变黑。

这是我正在使用的代码,但它看起来不正确。有人看到问题了吗?

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();
}

最佳答案

您需要将最后一个值的偏移量从 2 更改为 3。因为 pix[i+3] 控制 alpha channel 。

  if(r == r_val && g == g_val && b == b_val){ 
        pix[i] = 0;
        pix[i+1] = 0;
        pix[i+2] = 0;
        pix[i+3] = 0; // Change i+2, to i+3
    }

抱歉,您上一个问题是我的错。我在答案中提供的代码中有一个错字,但是 fiddle 工作得很好。

http://jsfiddle.net/loktar/BtbSM/

关于javascript - 如何在 IE9 中不是黑色的 html5 Canvas 中创建透明像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11473552/

相关文章:

javascript - Nodejs解码base64并使用流将它们保存到文件中

javascript - Node.js 异步替换字符串

javascript - axios post数组数据

javascript - 从 div 属性驱动 dimple.js 图表

html - 在同一行显示 2 个 DIV,其中一个是图片

html - 如何修复显示 :inline-block 中的间距

Android 4.0 与 Canvas.clipPath 的兼容性问题

javascript - 在 JavaScript 中计算 Canvas 数组中位数的有效方法

javascript - 将 canvas.focus() 放入 <div> 时防止滚动(仅在 IE 中失败)

javascript - Shiny 的 tabPanel 和 Google Analytics