Copy multiple HTML5 layered canvases to one image in JavaScript

十年热恋 提交于 2021-01-29 07:40:30

问题


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) Is there a way I can create a single image (using toDataURL()) of all of these canvases keeping the same order?

b) And, then how can I copy this image to a clipboard so that it can be pasted in other applications?


回答1:


Steps:

  1. Create a new Canvas (maybe hidden)
  2. Copy both canvas to the new canvas
  3. Copy to image using canvas.toDataURL()

See this fiddle: http://jsfiddle.net/137f623c/

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" />

And, the Script:

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()

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.




回答2:


As to part b) of your question...

You will have problems copying the merged canvas content to the clipboard because the required Clipboard API is not yet uniformly or well supported by modern browsers:

http://caniuse.com/#feat=clipboard

A workaround would be to:

  1. Upload the canvas.toDataURL to your server and save it as an image file,
  2. Download that image from the server and add it as an img element.

Then users can right-click-copy the img to their clipboard.



来源:https://stackoverflow.com/questions/30265024/copy-multiple-html5-layered-canvases-to-one-image-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!