【问题标题】:Javascript fill only certain part of canvas on clickJavascript仅在点击时填充画布的某些部分
【发布时间】:2021-11-27 23:22:45
【问题描述】:

我想在点击时使用 javascript 在画布绘图的特定部分进行着色。下面是我在圆内绘制正方形的代码。

<!DOCTYPE HTML>
<html>
    <head>
    </head>
    <body>
    
     <canvas width="300" height="300" id="myCanvas" style="border:1px solid #000000;"></canvas>
     <script>
        const canvas = document.getElementById('myCanvas');
        const context = canvas.getContext('2d');
        const centerX = canvas.width / 2;
        const centerY = canvas.height / 2;
        const radius = 70;

        context.beginPath();
        context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);

        context.rect(centerX-25, centerY-25, 50, 50)
        context.lineWidth = 5;
        context.strokeStyle = '#003300';
        context.stroke();
     </script>
    </body>
      
</html>

我的画布有这个:

点击正方形外但仍在圆圈内的区域后,我只想遮蔽该部分并拥有如下内容:

【问题讨论】:

  • 方格内的内容不被触碰重要吗?如果没有,您可以重新绘制圆形/正方形,但圆形填充为绿色,正方形填充为白色。
  • 感谢两位的回复。我会尝试洪水填充方法,因为它更具可扩展性。
  • 不要为此使用洪水填充。填充填充适用于您无法控制绘制的内容时,例如用户提供的位图图像或用户制作的过于复杂的形状。在你的情况下,你真的不需要这个......
  • 感谢您的告知和下面的解决方案,我会看看它。

标签: javascript html canvas html5-canvas


【解决方案1】:

您可以使用"evenodd" 填充规则简单地调用fill()。

但是,这会覆盖当前笔画的内半部分,为避免这种情况,您可以使用compositing 在当前图纸后面进行绘制:

const canvas = document.getElementById('myCanvas');
const context = canvas.getContext('2d');
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = 70;

context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);

context.rect(centerX-25, centerY-25, 50, 50)
context.lineWidth = 5;
context.strokeStyle = '#003300';
context.stroke();
context.fillStyle = "green";

canvas.onclick = ({ clientX, clientY }) => {
  const { left, top } = canvas.getBoundingClientRect();
  // if we're in the circle but not the inner rect
  if( context.isPointInPath( clientX - left, clientY - top, "evenodd" ) ) {
    // draw behind
    context.globalCompositeOperation = "destination-over";
    context.fill("evenodd");
    // do it only once
    canvas.onclick = null;
  }
};
&lt;canvas width="300" height="300" id="myCanvas" style="border:1px solid #000000;"&gt;&lt;/canvas&gt;

【讨论】:

  • 您能否解释一下evenodd 的作用或globalCompositeOperation 的作用?谢谢!
  • 我提供了文档的链接。
猜你喜欢
  • 2022-07-21
  • 2016-02-18
  • 1970-01-01
  • 1970-01-01
  • 2016-03-18
  • 1970-01-01
  • 1970-01-01
  • 2017-05-06
  • 1970-01-01
相关资源
最近更新 更多