【问题标题】:Make a Canvas Transparent [duplicate]使画布透明[重复]
【发布时间】:2015-03-31 23:49:38
【问题描述】:

我有一个 ID 为 #cnv 的画布。

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

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

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

这样做后,我将图像保存在物理磁盘中。下面是结果图像:

它的背景是白色的,不透明。我想让图像透明,除了画在其中的线条。我该怎么做?

【问题讨论】:

  • 请出示您用于绘图的代码。画布默认是透明的..

标签: javascript html5-canvas


【解决方案1】:

您可以使用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>

【讨论】:

    猜你喜欢
    • 2017-04-12
    • 2019-03-18
    • 2019-06-13
    • 2011-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-09
    • 2017-08-09
    相关资源
    最近更新 更多