使画布透明

时间:2015-03-31 09:44:25

标签: javascript html5-canvas

我有一张id为#cnv的画布。

<canvas id="cnv"></canvas>
<img id="img" src=""></img>

我使用下面的代码将画布转换为图像:

var a = document.getElementById("img");
a.src = document.getElementById("cnv").toDataURL();  

执行此操作后,我将图像保存在物理磁盘中。下面是结果图像:

enter image description here

它的背景是白色而不透明。我想让图像透明,除了绘制到它的线条。我该怎么做?

1 个答案:

答案 0 :(得分:0)

您可以使用context.getImageData来获取绘制到画布的图像的rgba像素数据。然后淘汰白色值 - 只留下黑线。

这是带注释的代码和演示:

// load the image into a new image object
var img=new Image();
img.crossOrigin='anonymous';
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/bk.png";
function start(){

  // create a canvas element
  var canvas=document.createElement("canvas");
  var ctx=canvas.getContext("2d");

  // size the canvas to the image size
  canvas.width=img.width;
  canvas.height=img.height;

  // draw the image onto the canvas
  ctx.drawImage(img,0,0);

  // get the pixel data of the canvas
  var imgData=ctx.getImageData(0,0,canvas.width,canvas.height);
  var data=imgData.data;

  // make any pure white pixel transparent: data[i+3]=0
  // Note: if needed, lower threshold slightly to catch "off-whites" 
  var threshold=255;
  for(var i=0;i<data.length;i++){
    if(data[i]==threshold && data[i+1]==threshold && data[i+2]==threshold){
      data[i+0]=0;
      data[i+1]=0;
      data[i+2]=0;
      data[i+3]=0;
    }
  }

  // put the modified pixels back on the canvas
  ctx.putImageData(imgData,0,0);

  // create an image from the canvas contents
  // and add that image to the page
  var img1=new Image();
  img1.onload=function(){
    document.body.appendChild(img1);
  }
  img1.src=canvas.toDataURL();


}
<h4>Image with pure white knocked out</h4>
<br>

相关问题