[英]Drawing a circle / arc on top of an image in HTML Canvas
我有一个简单的 canvas 作为背景,底部有一个图像,我正在尝试绘制一个与图像重叠的圆圈。 我有点不知道要使用哪个globalCompositeOperation
,以使弧/圆出现在 canvas 的图像顶部。
代码:
var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); var centerX = canvas.width / 2; var centerY = canvas.height / 2; var radius = 70; context.fillStyle = "#29BEF1"; context.fillRect(0, 0, 800, 131); var img = new Image; img.src = 'https://i.imgur.com/aN26XpH.png'; img.onload = function() { context.drawImage(img, 0, 29) } context.beginPath(); context.arc(800, -29, 87, 0, 2 * Math.PI); context.closePath(); context.fillStyle = '#FEDB62'; context.fill();
body { margin: 0px; padding: 0px; }
<canvas id="myCanvas" width="800" height="131"></canvas>
问题是由于加载图像是异步的,然后一旦加载并绘制它就会与已经绘制的内容重叠。
一个解决方案是将绘制太阳的代码移动到onload
回调中。
img.onload = function() {
// draw image
context.drawImage(img, 0, 29)
// draw sun
context.beginPath();
context.arc(800, -29, 87, 0, 2 * Math.PI);
context.closePath();
context.fillStyle = '#FEDB62';
context.fill();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.