簡體   English   中英

如何繪制三個圓圈並僅將兩個圓圈連接起來?

[英]How to draw three circles and connect only two by line?

我試着畫出三個點,然后只用線連接其中兩個。

我的嘗試看起來像這樣

為什么我在 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;
}

您應該在自己的路徑中擁有每個圓圈:

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM