使用图像绘制HTML5

时间:2014-09-18 09:21:05

标签: javascript jquery html html5 html5-canvas

我有一张图片,我希望能够在上面画画。我知道如何在画布上绘画,但我的主要问题是,目前,当我点击图像时,它不是画布而是图像。如何将画布放在图像顶部以便我可以在上面绘图?

我的HTML中有这个:

<div class="image">
    <img src="http://upload.wikimedia.org/wikipedia/en/a/aa/Bart_Simpson_200px.png" alt="Bart" class="img-responsive"/>
    <canvas></canvas>
    <div class="caption text-center">Bart Simpson</div>
</div>

1 个答案:

答案 0 :(得分:2)

您要做的是等到图像加载完毕。使用drawImage并在画布上绘制它。然后做你想用帆布做的其他事情。最后,您可以使用toDataURL再次导出画布并设置图像的来源

&#13;
&#13;
var imageNode = document.getElementById('image');
var image = new Image();
image.src = "http://upload.wikimedia.org/wikipedia/en/a/aa/Bart_Simpson_200px.png";
image.onload = function() {
	var canvas = document.getElementById('imageCanvas');
	canvas.width = image.width;
	canvas.height = image.height;
	var ctx = canvas.getContext('2d');
	ctx.drawImage(image, 0, 0);

	// Do something like painting a green hat
	ctx.moveTo(35, 50);
	ctx.lineTo(85, 10);
	ctx.lineTo(135, 50);
	ctx.closePath();
	ctx.fillStyle = "#009900";
	ctx.fill();

	var dataURL = canvas.toDataURL();
	imageNode.src = dataURL;
}
&#13;
#image {
    display: none;
}
&#13;
	<img src="http://upload.wikimedia.org/wikipedia/en/a/aa/Bart_Simpson_200px.png" alt="Bart" id="image" class="img-responsive" />
<canvas id="imageCanvas"></canvas>
&#13;
&#13;
&#13;