gpt4 book ai didi

javascript - 使用 HTML5 在图像上绘图

转载 作者:行者123 更新时间:2023-11-30 17:17:05 27 4
gpt4 key购买 nike

我有一张图片,我想在上面画画。我知道如何在 Canvas 上绘图,但我的主要问题是目前,当我单击图像时,它不是 Canvas 而是图像。如何将 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>

最佳答案

您要做的是等待图像加载完毕。使用 drawImage 并将其绘制在 Canvas 上。然后用你的 Canvas 做任何你想做的事情。最后,您可以使用 toDataURL 再次导出 Canvas 并设置图像的来源

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;
}
#image {
display: none;
}
	<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>

关于javascript - 使用 HTML5 在图像上绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25908809/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com