HTML Canvas - 仅在重叠的半透明弧线外部绘制笔划

问题描述 投票:0回答:1

我正在尝试使用以下代码在 HTML 画布上仅在形成的形状的外部上绘制 2 个半透明圆圈。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Canvas Arcs</title>
  <style>
    body {
      margin: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      background-color: #f0f0f0;
    }
  </style>
</head>
<body>
  <canvas id="myCanvas" width="400" height="200"></canvas>

  <script>
    // Get the canvas element and its context
    const canvas = document.getElementById('myCanvas');
    const context = canvas.getContext('2d');
    context.fillStyle = 'rgba(255, 0, 0, 0.5)';
    
    context.arc(100, 100, 80, 0, Math.PI * 2);
    context.arc(200, 100, 80, 0, Math.PI * 2);
    
    context.stroke()
    context.fill();
  </script>
</body>
</html>

我对结果的问题是,笔划是分别在每个弧上绘制的,以及我假设“闭合路径”的平行线。

所需的结果如下图所示。我能够通过填充为纯色而不是半透明来实现此结果。然而,在我的实际应用中,填充需要是半透明的,以显示绘制形状下方的其他元素。

javascript html html5-canvas
1个回答
0
投票

我尝试根据期望的结果来解决它:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Canvas Arcs</title>
  <style>
    body {
      margin: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      background-color: #f0f0f0;
      background-image: url("https://www.w3schools.com/cssref/paper.gif");
    }

 
  </style>
</head>
<body>
  <canvas id="myCanvas" width="400" height="200"></canvas>

  <script>
    // Get the canvas element and its context
    const canvas = document.getElementById('myCanvas');
    const context = canvas.getContext('2d');
    context.fillStyle = 'rgba(255, 0, 0, 0.1)';
    context.strokeStyle = `hsla(0, 100%, 50%, 0.0)`;
    
    context.arc(100, 100, 80, 0, Math.PI * 2);
    context.arc(200, 100, 80, 0, Math.PI * 2);

    context.stroke()
    context.fill();
  </script>
</body>
</html>

© www.soinside.com 2019 - 2024. All rights reserved.