从没有canvas元素的HTML Canvas ImageData创建Base64数据

时间:2016-08-05 05:47:46

标签: javascript html5 canvas html5-canvas base64

我有一个画布元素CA,我在那里画了一些奇特的东西。然后,我从canvas IDA对ImageData CA运行一种过滤器,并创建新的,已修改的ImageData IDB。现在,我希望将IDB转换为base64字符串,而无需第二个帮助画布 CB

我在此主题中找到的所有内容都显示整个画布正在转换为dataURL。没有CB可能吗?怎么样?



var CA = document.getElementById("CA");
var ctx = CA.getContext("2d");

ctx.beginPath();
ctx.fillRect(100, 100, 100, 100);
ctx.stroke();
ctx.closePath();

var srcImg = ctx.getImageData(0, 0, CA.width, CA.height),
    srcData = srcImg.data,
    dstImg = ctx.createImageData(srcImg),
    dstData = dstImg.data;

for (var i=0, maxI=srcData.length; i<maxI; i+=4) {
  //invert
  if (srcData[i+3] > 0) {    
    dstData[i] = dstData[i+1] = dstData[i+2] = 255;
    dstData[i+3] = 0;
  }
  else {
    dstData[i] = dstData[i+1] = dstData[i+2] = 0;         
    dstData[i+3] = 255;
  }
}

//how to create base64 from dstImg??
//...

//just for visualization
document.getElementById("CB").getContext("2d").putImageData(dstImg, 0, 0);
&#13;
canvas {
  border : 1px solid;
}
&#13;
<canvas id="CA" width="400" height="300"></canvas>
<!-- I'd like to avoid this helper canvas CB -->
<canvas id="CB" width="400" height="300"></canvas>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

您可以克隆原始<canvas>元素,.putImageData()clone.toDataURL()

&#13;
&#13;
var CA = document.getElementById("CA");
var ctx = CA.getContext("2d");

ctx.beginPath();
ctx.fillRect(100, 100, 100, 100);
ctx.stroke();
ctx.closePath();

var srcImg = ctx.getImageData(0, 0, CA.width, CA.height),
  srcData = srcImg.data,
  dstImg = ctx.createImageData(srcImg),
  dstData = dstImg.data;

for (var i = 0, maxI = srcData.length; i < maxI; i += 4) {
  //invert
  if (srcData[i + 3] > 0) {
    dstData[i] = dstData[i + 1] = dstData[i + 2] = 255;
    dstData[i + 3] = 0;
  } else {
    dstData[i] = dstData[i + 1] = dstData[i + 2] = 0;
    dstData[i + 3] = 255;
  }
}

var clone = document.getElementById("CA").cloneNode();
var ctx = clone.getContext("2d");
ctx.putImageData(dstImg, 0, 0);
var url = clone.toDataURL();
var img = document.createElement("img");
img.onload = function() {
  document.body.appendChild(this);
  console.log(url);
}
img.src = url;
&#13;
canvas {
  border: 1px solid;
}
&#13;
<canvas id="CA" width="400" height="300"></canvas>
&#13;
&#13;
&#13;