问题
I'm in a situation where I generate multiple canvas (~200) where I draw an image snapped from the user webcam (experimentation of the "photo finish" technique).
I have to export those canvas as a simple jpeg as shown in the following image.
You can also see how it should visually look like (multiple stripe as multiple canvas, those I have to export as one and only Jpg).
Any idea or direction of how proceed?
Thanks in advance!
AW.
回答1:
Simply use drawImage(). It accepts an other canvas as bitmap source (first param).
So you'll need to
- determine the size of your final canvas
- determine the position of every smaller canvases
- draw these
// sizes of each strip
var width = 10;
var height = 200;
// we'll store each 'strip' canvas in an Array
var strips = [];
for(var i = 0; i<60; i++) {
// fill the Array
strips.push(makeStrip());
// populate the doc
container.appendChild(strips[i]);
}
// our merging canvas
var merger = document.createElement('canvas');
merger.width = width * 60; // sum of widths
merger.height = height;
var ctx = merger.getContext('2d');
// iterate through all our strips
strips.forEach(function drawToMerger(small, i) {
// simply draw at index * width
ctx.drawImage(small, i * width, 0);
});
// export
merger.toBlob(function(blob) {
img.src = URL.createObjectURL(blob);
});
// Strip builder
function makeStrip() {
var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext('2d');
var grad = ctx.createLinearGradient(0,0,0,canvas.height);
grad.addColorStop(0, randColor());
grad.addColorStop(1, randColor());
ctx.fillStyle = grad;
ctx.fillRect(0,0,canvas.width,canvas.height);
return canvas;
}
function randColor() {
return '#' + (Math.random()).toString(16).substr(2,6);
}
#container{white-space:nowrap}
canvas:hover{opacity:.7}
img{border: 3px solid #00FF00}
Strips:
<div id="container"></div>
Merged Image:
<img id="img">
But note that you may also want to work on a single canvas from the beginning, it would free up some memory.
来源:https://stackoverflow.com/questions/53164342/merge-multiple-canvas-in-one-to-export-it-using-vanilla-javascript