在JavaScript中将多个HTML5分层画布复制到一张图像 [英] Copy multiple HTML5 layered canvases to one image in JavaScript
问题描述
我有多个HTML5画布,它们彼此叠放.顺序很重要.画布2将放置在画布1上,依此类推.
I have multiple HTML5 canvases which are placed on top of one another. The order is important. Canvas 2 will be placed on Canvas 1 and so forth.
a)有什么方法可以创建所有这些画布的单个图像(使用toDataURL()),并保持相同的顺序吗?
a) Is there a way I can create a single image (using toDataURL()) of all of these canvases keeping the same order?
b)然后,如何将该图像复制到剪贴板,以便可以将其粘贴到其他应用程序中?
b) And, then how can I copy this image to a clipboard so that it can be pasted in other applications?
推荐答案
步骤:
- 创建一个新的Canvas(可能已隐藏)
- 将两个画布都复制到新画布中
- 使用
canvas.toDataURL()
复制到图像
- Create a new Canvas (maybe hidden)
- Copy both canvas to the new canvas
- Copy to image using
canvas.toDataURL()
查看此小提琴: http://jsfiddle.net/137f623c/
假设您有3个画布(2个源和1个合并-如果需要,可以将其隐藏)和一个图像:
Let's say you have 3 canvas (2 source and 1 combined - hide this if you want) and an image:
<canvas id="myCanvas1" width="200" height="200"></canvas>
<canvas id="myCanvas2" width="400" height="200"></canvas>
<canvas id="combined" width="400" height="200"></canvas>
<img src="" id="image" />
然后,脚本:
var canvas1 = document.getElementById("myCanvas1");
var ctx1 = canvas1.getContext("2d");
ctx1.fillStyle = "red";
ctx1.fillRect(10,10,100,100);
var canvas2 = document.getElementById("myCanvas2");
var ctx2 = canvas2.getContext("2d");
ctx2.fillStyle = "blue";
ctx2.fillRect(50,50,300,100);
var combined = document.getElementById("combined");
var ctx = combined.getContext("2d");
ctx.drawImage(canvas1, 0, 0); //Copying Canvas1
ctx.drawImage(canvas2, 0, 0); //Copying Canvas2
document.getElementById("image").src = combined.toDataURL()
别忘了考虑MarkE的答案(针对b部分),并查看浏览器之间的兼容性.就复制而言,我发现大多数现代浏览器在单击鼠标右键时均具有 Copy Image
.对于旧的浏览器,:\上载到服务器并下载可能是解决方案.
Don't forget consider MarkE's Answer (for part b) and also see for compatibility among browsers. As far for copying I see that most modern browsers have Copy Image
when right clicked. For old browsers, :\ uploading to server and downloading might be the solution.
这篇关于在JavaScript中将多个HTML5分层画布复制到一张图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!