我想绘制一个带有圆孔的黑色实心矩形,通过孔可以看到背景图像。有没有简单的方法可以做到这一点?
最佳答案
用路径绘制外部形状,又名 moveTo
、lineTo
等。然后在该形状内绘制负形状,但在相反的顺时针/逆时针方向。然后调用 fill()
。
下面是一个绘制带圆孔的圆的示例。
<html><head></head><body>
<canvas id="canvas" width=600 height=600></canvas>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var width = canvas.width, height = canvas.height;
var context = canvas.getContext("2d");
// draw a diagonal line just to demonstrate the transparency later
context.beginPath();
context.moveTo(width/2 - height/2, 0);
context.lineTo(width/2 + height/2, height);
context.lineWidth = 3;
context.strokeStyle = "#0f0";
context.stroke();
// draw a circle with a hole in it
context.beginPath();
context.arc(width/2, height/2, height*3/8, 0, 2*Math.PI);
context.arc(width/2, height/2, height*1/8, 0, 2*Math.PI, true);
context.fillStyle = "#555";
context.fill();
</script>
</body>
</html>
关于javascript - 在 HTML <canvas> 上绘制 "negative space",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5546396/