如何将'canvas'中的图像附加到'img'元素中

时间:2017-09-27 11:08:15

标签: javascript canvas html5-canvas

我有一个HTML代码如下:

<canvas id="canvas1" width="200" height="200"></canvas>

和javaScript代码如下:

var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');
var src="https://vignette2.wikia.nocookie.net/mint524/images/d/d7/Sky.jpg/revision/latest?cb=20160706152654.jpg"

var image = new Image();
image.onload = function(){
  ctx.drawImage(image,0,0,50,50);  
}
ctx.fillRect(50,50,50,50);
image.src = src

var img = new Image();
img.src = can.toDataURL();
document.body.appendChild(img);

我想将canvas转换为img元素,但我发现无法将画布中的图像附加到img元素。已解决的代码位于here。 任何人都可以提供一些建议吗?

3 个答案:

答案 0 :(得分:1)

如果您确保图片没有受到污染 - 请参阅此问题并回答:Tainted canvases may not be exported,然后您可以更改代码,以便在加载旧图片后创建新图片:

var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');
var src = "//i.imgur.com/fHyEMsl.jpg";

var image = new Image();
image.crossOrigin = "anonymous";  

image.onload = function() {
  ctx.drawImage(image, 0, 0, 200, 200);

  var img = new Image();    // move this into the onload of the image to make sure the canvas has been drawn
  img.src = can.toDataURL("image/png");
  document.body.appendChild(img);
}
image.src = src;
<p>Canvas:</p>
<canvas id="canvas1" width="200" height="200"></canvas>
<p>Image should appear below:</p>

答案 1 :(得分:0)

画布的行为与图像非常相似。

当您使用canvas.toDataURL并将其分配给image.src时,您会浪费大量内存。图像将从dataURL解码,并使用相同数量的RAM作为画布的像素,但dataURL也将保留在内存中。

Base64编码不是为紧凑而设计的。每个Base64字符编码6位,但每个Javascript字符使用16位。这使得dataURL比存储在磁盘上的情况大2.667倍,并且在某些极端情况下可能比原始像素数据大。

您可以使用canvas.toBlob()并从blob构造图像,这样可以避免redundent dataURL的内存开销。但是你仍然没有将彩色画布编码成图像。

最简单的解决方案是将画布视为图像。像对待图像一样将它添加到DOM中,并省去了尝试编码和解码图像格式的麻烦。你想从画布不会做的图像中得到什么? src?好吧,问题是不是。

const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
ctx.fillRect(0,0,300,150);
ctx.fillStyle = "white";
ctx.fillRect(10,10,280,130);
ctx.fillStyle = "Blue";
ctx.fillRect(15,15,270,120);
ctx.fillStyle = "white";
ctx.font = "28px arial";
ctx.fillText("Look like an Image", 20, 40);
ctx.fillText("Acts like an Image", 20, 70);
ctx.font = "20px arial";
ctx.fillText("Who cares if it's a Canvas", 20, 100);
ctx.textAlign = "right";
ctx.fillText("", 270, 125);


function copyCanvas(canvas){
    const c = canvas.cloneNode();
    c.getContext("2d").drawImage(canvas,0,0);
    return c;
}
document.body.appendChild(copyCanvas(canvas));

答案 2 :(得分:-2)

出于安全原因,您的本地驱动器被声明为“其他域”并且会污染画布。

(那是因为您最敏感的信息可能在您的本地驱动器上!)。

在测试时尝试这些解决方法:

  • 包装超时从画布中导出img
  • 将所有与页面相关的文件(.html,.jpg,.js,.css等)放在您的 桌面(不在子文件夹中)。
  • 将您的图片发布到支持跨域共享的网站(例如 dropbox.com)。请确保将图像放在Dropbox的公用文件夹中 并在下载图像时设置交叉原点标志(var img = new Image(); img.crossOrigin =“anonymous”...)

setTimeout(
  function(){
  var can = document.getElementById('canvas1');
  var img = new Image();
  img.src = can.toDataURL();
  document.body.appendChild(img);
},2000);

相关问题