【问题标题】:How to draw three circles and connect only two by line?如何绘制三个圆圈并仅将两个圆圈连接起来?
【发布时间】:2021-06-21 08:35:47
【问题描述】:

我尝试画出三个点,然后只用线连接其中两个。

我的尝试看起来像this

为什么我在 x0、x1、x2 坐标中得到错误的圆圈?

for (let x = 0; x < width; x += offsetX) {
  ctx.arc(x0, y0, 1, 0, 2 * Math.PI, false);
  ctx.arc(x1, y1, 1, 0, 2 * Math.PI, false);
  ctx.arc(x2, y2, 1, 0, 2 * Math.PI, false);
  ctx.fill();

  ctx.beginPath();
  ctx.moveTo(x0, y0);
  ctx.lineTo(x2, y2);
  ctx.moveTo(x2, y2);
  ctx.lineTo(x1, y1);
  ctx.stroke();

  x0 += offsetX;
  x1 += offsetX;
  x2 += offsetX;
}

【问题讨论】:

    标签: html canvas html5-canvas


    【解决方案1】:

    你应该让每个圆圈都有自己的路径:

    ctx.beginPath();
    ctx.arc(x0, y0, 4, 0, 2 * Math.PI);
    ctx.fill();
    
    ctx.beginPath();
    ctx.arc(x1, y1, 4, 0, 2 * Math.PI);
    ctx.fill();
    

    这是您的代码的简化版本:

    let canvas = document.createElement("canvas");
    canvas.width = canvas.height = 200;
    ctx = canvas.getContext("2d");
    ctx.translate(5, 5);
    
    let triangleWidth = 20;
    let offset = 50;
    
    let y0 = 1;
    let y1 = triangleWidth;
    let y2 = triangleWidth / 2;
    
    function draw() {
      for (let y = 0; y < canvas.height; y++) {
        x0 = triangleWidth;
        x1 = triangleWidth;
        x2 = 0;
    
        for (let x = 0; x < canvas.width; x += offset) {
          ctx.beginPath();
          ctx.arc(x0, y0, 4, 0, 2 * Math.PI);
          ctx.fill();
          ctx.beginPath();
          ctx.arc(x1, y1, 4, 0, 2 * Math.PI);
          ctx.fill();
          ctx.beginPath();
          ctx.arc(x2, y2, 4, 0, 2 * Math.PI);
          ctx.fill();
    
          ctx.beginPath();
          ctx.moveTo(x0, y0);
          ctx.lineTo(x2, y2);
          ctx.moveTo(x2, y2);
          ctx.lineTo(x1, y1);
          ctx.stroke();
    
          x0 += offset;
          x1 += offset;
          x2 += offset;
        }
        y0 += offset;
        y1 += offset;
        y2 += offset;
      }
    }
    
    draw();
    document.body.appendChild(canvas);

    【讨论】:

      猜你喜欢
      • 2017-01-04
      • 2018-12-15
      • 1970-01-01
      • 1970-01-01
      • 2015-10-20
      • 1970-01-01
      • 2012-11-12
      • 2013-12-02
      • 1970-01-01
      相关资源
      最近更新 更多