HTML:
<img src="http://lorempixel.com/100/100/">
<img src="http://lorempixel.com/100/100/">
<img src="http://lorempixel.com/100/100/">
<img src="http://lorempixel.com/100/100/">
<canvas id="canvas" width="0" height="0"></canvas>
使用Javascript:
var images = document.getElementsByTagName('img');
var canvas = document.getElementById('canvas');
for (var i = 0; i < images.length; i++) {
canvas.getContext('2d').drawImage(images[i], canvas.width, canvas.height);
canvas.height = canvas.height + images[i].height;
canvas.width = images[i].width;
}
这是小提琴:
https://jsfiddle.net/083bapwz/29/
为什么画布不可见或我猜,甚至没画画?我希望它一个接一个地绘制,首先在顶部,其他人在底部。
答案 0 :(得分:0)
一些事情。
首先,更改画布宽度/高度尺寸会重置所有现有画布状态。它是clearRect的一种更黑客(并且支持度较低)的形式。
以下面的代码段为例:
var images = document.getElementsByTagName('img');
var canvas = document.getElementById('canvas');
var canvas2 = document.getElementById('canvas2');
var canvas3 = document.getElementById('canvas3');
var ctx1 = canvas.getContext('2d');
var ctx2 = canvas2.getContext('2d');
var ctx3 = canvas3.getContext('2d');
// wont draw
ctx1.moveTo(0, 0);
ctx1.lineTo(100, 100);
ctx1.stroke();
canvas.width = 300;
// wont draw
ctx2.moveTo(0, 0);
ctx2.lineTo(50, 50);
ctx2.stroke();
canvas2.height = 100;
// will draw
ctx3.moveTo(0, 0);
ctx3.lineTo(100, 100);
ctx3.stroke();
&#13;
#canvas{border: 1px solid red;}
#canvas2{border: 1px solid blue;}
#canvas3{border: 1px solid green;}
&#13;
<canvas id="canvas" width="200" height="200"></canvas>
<canvas id="canvas2" width="200" height="200"></canvas>
<canvas id="canvas3" width="200" height="200"></canvas>
&#13;
换句话说,不要调整画布大小,因为最后一张图像是唯一要绘制的图像。
其次,您要告诉图像在canvas.width和canvas.height的(x,y)位置绘制。这意味着你将在这里绘制图像:
您需要为图像绘制指定(顶部,左侧)x / y值。
希望这有帮助。
编辑:
可能的解决方案可能是以下demo:
var images = document.getElementsByTagName('img');
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var imageArray = Array.from(images);
// add all image heights together
var canvasHeight = imageArray.reduce(function (acc, img) {
acc += img.height;
return acc;
}, 0);
// just use first image as the width for this example
var canvasWidth = imageArray[0].width;
// set all canvas state prior to draws
canvas.height = canvasHeight;
canvas.width = canvasWidth;
var top = 0;
for (var i = 0; i < imageArray.length; i++) {
var image = imageArray[i];
// use x of 0 to draw on left most of canvas
canvas.getContext('2d').drawImage(image, 0, top);
top += image.height;
}