2012-07-13 63 views
1

我想在畫布上的另一個圖像上繪製圖像,並在第一個圖像中嘗試刪除白色像素並使它們透明,但他們變黑了。如何在HTML5畫布中創建在IE9中不是黑色的透明像素

這是我正在使用的代碼,但它看起來不正確。有沒有人看到這個問題?

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

回答

4

您需要將最後一個值的偏移量從2更改爲3.由於控制着alpha通道。

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 
    } 

對不起,這是我最後一個問題的錯。在我的答案中提供的代碼中存在拼寫錯誤,但小提琴完美奏效。

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