简体   繁体   English

如何将数据从一个画布复制到另一个画布

[英]How to copy data from one canvas to another

I have forms with arbitrary numbers of canvases. 我有带有任意数量的画布的表格。 Once one is filled out I would like to copy it to any other canvas that is interacted with. 填写完毕后,我想将其复制到与之交互的其他任何画布上。

I have currently 我目前有

When one canvase is closed I save the canvas data 当一个画布关闭时,我保存画布数据

sourceCanvas = $(this).find('canvas')[0];

Then when the next one loads (they are in modals) 然后在下一个加载时(它们是模态的)

I try to populate it like this 我尝试这样填充

var destCtx = $(this).find('canvas')[0].getContext('2d');
destCtx.drawImage(sourceCanvas, 0, 0);

I am getting this error 我收到此错误

Uncaught 未捕获

TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)' TypeError:无法在'CanvasRenderingContext2D'上执行'drawImage':提供的值不是'(CSSImageValue或HTMLImageElement或HTMLVideoElement或HTMLCanvasElement或ImageBitmap或OffscreenCanvas)类型的值

Is ('canvas')[0] the wrong thing to grab? ('canvas')[0]是抓错的东西吗? should I be getting something else in the canvas element? 我应该在canvas元素中添加其他内容吗?

Thanks! 谢谢!

When one canvase is closed I save the canvas data 当一个画布关闭时,我保存画布数据

sourceCanvas = $(this).find('canvas')[0];

I think that your code is not accessing the image data in the source canvas. 我认为您的代码未访问源画布中的图像数据。 Call getImageData() on the context of the source canvas then get call putImageData() on the context of the destination canvas . 在源画布的上下文中调用getImageData() ,然后在目标画布的上下文中调用putImageData() Below is a simple example which copies the image data from canvas1 into both canvas1 (at a different location for illustration) and also into canvas2. 下面是一个简单的示例,该示例将图像数据从canvas1复制到canvas1(在用于说明的其他位置)也复制到canvas2。

Also, check out this excellent text on HTML5 Canvas . 另外,请查看HTML5 Canvas上的出色文字。

<html>
<body>

<canvas id="canvas1" width="300" height="150" style="border:1px solid #f00;">no canvas</canvas>

<canvas id="canvas2" width="300" height="150" style="border:1px solid #00f;">no canvas</canvas>


<script>
var c1 = document.getElementById("canvas1");
var c2 = document.getElementById("canvas2");
var ctx1 = c1.getContext("2d");
var ctx2 = c2.getContext("2d");
ctx1.fillStyle = "red";
ctx1.fillRect(10, 10, 50, 50);

function copy() {
    var imgData = ctx1.getImageData(10, 10, 50, 50);
    ctx1.putImageData(imgData, 10, 70);
    ctx2.putImageData(imgData, 10, 70);
}
</script>

<button onclick="copy()">Copy</button>

</body>
</html>

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM