使用香草Javascript将多个画布合并(导出)
我处于生成多个画布(约200个)的情况,在其中我绘制了从用户网络摄像头捕捉到的图像(照片修整"技术的实验).
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).
我必须将这些画布导出为简单的jpeg,如下图所示.
I have to export those canvas as a simple jpeg as shown in the following image.
您还可以看到它的外观(多条纹多画布,我必须将它们导出为一个和唯一的Jpg).
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?
提前谢谢!
啊.
只需使用 drawImage().它接受另一个画布作为位图源(第一个参数).
Simply use drawImage(). It accepts an other canvas as bitmap source (first param).
所以您需要
- 确定最终画布的大小
- 确定每个较小的画布的位置
- 画这些
// 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.