Merge Multiple Canvas In One (to Export It) Using Vanilla Javascript
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 th
Solution 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 stripvar width = 10;
var height = 200;
// we'll store each 'strip' canvas in an Arrayvar strips = [];
for(var i = 0; i<60; i++) {
// fill the Array
strips.push(makeStrip());
// populate the doc
container.appendChild(strips[i]);
}
// our merging canvasvar 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(functiondrawToMerger(small, i) {
// simply draw at index * width
ctx.drawImage(small, i * width, 0);
});
// export
merger.toBlob(function(blob) {
img.src = URL.createObjectURL(blob);
});
// Strip builderfunctionmakeStrip() {
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;
}
functionrandColor() {
return'#' + (Math.random()).toString(16).substr(2,6);
}
#container{white-space:nowrap}
canvas:hover{opacity:.7}
img{border: 3px solid #00FF00}
Strips:
<divid="container"></div>
Merged Image:
<imgid="img">
But note that you may also want to work on a single canvas from the beginning, it would free up some memory.
Post a Comment for "Merge Multiple Canvas In One (to Export It) Using Vanilla Javascript"