javascript - 在 HTML <canvas> 上绘制 "negative space"

标签 javascript html canvas

我想绘制一个带有圆孔的黑色实心矩形,通过孔可以看到背景图像。有没有简单的方法可以做到这一点?

最佳答案

用路径绘制外部形状,又名 moveTolineTo 等。然后在该形状内绘制负形状,但在相反的顺时针/逆时针方向。然后调用 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/

相关文章:

javascript - 将元素附加到数组 : Differences between direct assignment and `push` ?

javascript - 为什么当应用程序关闭时 componentWillUnmount 不会在 React 根组件中触发

javascript - 无法使用 History.js 实现历史记录

html - 在鼠标悬停时更改菜单颜色

javascript - json数据未解析成

jQuery - 如果输入文本等于答案则添加类

javascript - 使用 jQuery 创建 Accordion ,但得到 "$ is not defined"

html - 如何在 html5 canvas 中对齐文本?

javascript - 关于 javascript-canvas 对象的问题(保存、转换、恢复)

Android 弯曲 View Canvas 以提供 curl 效果