问题
I have 3 canvas i.e. canvasTarget, canvasTarget2, canvasTarget3 as shown below:
var canvas = document.getElementById("canvasTarget");
var img = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
var canvas2 = document.getElementById("canvasTarget2");
var img2 = canvas2.toDataURL("image/png").replace("image/png", "image/octet-stream");
var canvas3 = document.getElementById("canvasTarget3");
var img3 = canvas3.toDataURL("image/png").replace("image/png", "image/octet-stream");
I want to combine these canvas elements into one and download as JPEG or PDF file. I am using /html2canvas.js for downloading this. Any immediate response will be appreciated.
回答1:
So you've rendered your canvases, but it's not clear how you want to combine them - overlaid, side-by-side? In either case you can use Canvas.context.drawImage()
to add them to a new canvas object, and then use the Canvas.toDataURL()
method to return the, erm, dataURL of the new canvas.
Something like this perhaps...
/* assumes each canvas has the same dimensions */
var overlayCanvases = function(cnv1, cnv2, cnv3) {
var newCanvas = document.createElement('canvas'),
ctx = newCanvas.getContext('2d'),
width = cnv1.width,
height = cnv1.height;
newCanvas.width = width;
newCanvas.height = height;
[cnv1, cnv2, cnv3].forEach(function(n) {
ctx.beginPath();
ctx.drawImage(n, 0, 0, width, height);
});
return newCanvas.toDataURL();
};
/* assumes each canvas has the same width */
var verticalCanvases = function(cnv1, cnv2, cnv3) {
var newCanvas = document.createElement('canvas'),
ctx = newCanvas.getContext('2d'),
width = cnv1.width,
height = cnv1.height + cnv2.height + cnv3.height;
newCanvas.width = width;
newCanvas.height = height;
[{
cnv: cnv1,
y: 0
},
{
cnv: cnv2,
y: cnv1.height
},
{
cnv: cnv3,
y: cnv1.height + cnv2.height
}].forEach(function(n) {
ctx.beginPath();
ctx.drawImage(n.cnv, 0, n.y, width, n.cnv.height);
});
return newCanvas.toDataURL();
};
/* USAGE */
var dURL1 = overlayCanvases(canvas1,canvas2,canvas3);
var dURL2 = verticalCanvases(canvas1,canvas2,canvas3);
The overlayCanvases()
function will place the canvases on top of each other, so the order of the arguments is important. The verticalCanvases()
will align the canvas vertically and in descending order. The important thing to notice here is that Canvas.context.drawImage()
allows you to paint one canvas into another - relative positioning can be jiggled to suit your purposes.
Functions above Fiddled : https://jsfiddle.net/BnPck/cyLrmpjy/
来源:https://stackoverflow.com/questions/38851963/how-to-combine-3-canvas-html-elements-into-1-image-file-using-javascript-jquery