如何在本地将一个画布的内容复制到另一个画布 [英] How to Copy Contents of One Canvas to Another Canvas Locally

查看:96
本文介绍了如何在本地将一个画布的内容复制到另一个画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想复制一个画布的所有内容并将它们转移到客户端的另一个所有内容.我认为我会使用 canvas.toDataURL()context.drawImage() 方法来实现这一点,但我遇到了一些问题.

I'd like to copy ALL contents of one canvas and transfer them to another all on the client-side. I would think that I would use the canvas.toDataURL() and context.drawImage() method to implement this but I am running into a few issues.

我的解决方案是获取 Canvas.toDataURL() 并将其存储在 Javascript 中的 Image 对象中,然后使用 context.drawImage() 方法放置回来了.

My solution would be to get Canvas.toDataURL() and store this in an Image object in Javascript, and then use the context.drawImage() method to place it back.

但是,我相信 toDataURL 方法返回一个带有 "data:image/png;base64," 的 64 位编码标签.这似乎不是一个有效的标签,(我总是可以使用一些 RegEx 来删除它),但是在 "data:image/png;base64," 子字符串之后的 64 位编码字符串是一个有效的图像?我可以说image.src=iVBORw...ASASDAS,然后把它画回到画布上吗?

However, I believe the toDataURL method returns a 64 bit encoded tag with "data:image/png;base64," prepended to it. This does not seem to be a valid tag, (I could always use some RegEx to remove this), but is that 64 bit encoded string AFTER the "data:image/png;base64," substring a valid image? Can I say image.src=iVBORw...ASASDAS, and draw this back on the canvas?

我查看了一些相关问题:使用base64

I've looked at some related issues: Display canvas image from one canvas to another canvas using base64

但解决方案似乎并不正确.

But the solutions don't appear to be correct.

推荐答案

实际上您根本不需要创建图像.drawImage() 将接受一个 Canvas 以及一个 Image 对象.

Actually you don't have to create an image at all. drawImage() will accept a Canvas as well as an Image object.

//grab the context from your destination canvas
var destCtx = destinationCanvas.getContext('2d');

//call its drawImage() function passing it the source canvas directly
destCtx.drawImage(sourceCanvas, 0, 0);

比使用 ImageData 对象或 Image 元素快得多.

Way faster than using an ImageData object or Image element.

请注意,sourceCanvas 可以是 HTMLImageElementHTMLVideoElementHTMLCanvasElement.正如 Dave 在此答案下方的评论中所述,您不能使用画布绘图上下文作为您的来源强>.如果您有一个画布绘图上下文而不是创建它的画布元素,则在 context.canvas 下的上下文中有对原始画布元素的引用.

Note that sourceCanvas can be a HTMLImageElement, HTMLVideoElement, or a HTMLCanvasElement. As mentioned by Dave in a comment below this answer, you cannot use a canvas drawing context as your source. If you have a canvas drawing context instead of the canvas element it was created from, there is a reference to the original canvas element on the context under context.canvas.

这是一个 jsPerf 来演示为什么这是克隆画布的唯一正确方法:http://jsperf.com/copying-a-canvas-element

Here is a jsPerf to demonstrate why this is the only right way to clone a canvas: http://jsperf.com/copying-a-canvas-element

这篇关于如何在本地将一个画布的内容复制到另一个画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆