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

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

问题描述

我想复制一个画布的所有内容,并将它们转移到客户端的另一个。我会认为我会使用 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 方法返回一个64位编码标签data:image / png; base64,前置它。这似乎不是一个有效的标签,(我可以总是使用一些RegEx删除这个),但是64位编码字符串之后data:image / png; base64,子字符串有效的图像?我可以说 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 以及映像 object。

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 元素。

请注意, sourceCanvas HTMLImageElement HTMLVideoElement HTMLCanvasElement 。正如 Dave 在此答案下面的注释中提到的,您不能使用画布图上下文作为源强>。如果你有一个画布上下文,而不是从它创建的canvas元素,则在 context.canvas 下的上下文中有一个对原始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天全站免登陆