萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

HTML5 Canvas 繪製帶箭頭虛線:互動式拖曳與點擊延伸

Canvas 原生無虛線 API,本文示範如何擴充 CanvasRenderingContext2D.prototype.dashedLine 繪製虛線,並結合三角函數計算箭頭角度,實現滑鼠點擊任意處箭頭自動延伸指向。

虛線繪製原型擴充

if (CanvasRenderingContext2D.prototype.lineTo) {
  CanvasRenderingContext2D.prototype.dashedLine = function(x, y, x2, y2, dashArray) {
    if (!dashArray) dashArray = [10, 5];
    const dashCount = dashArray.length;
    this.moveTo(x, y);
    const dx = x2 - x, dy = y2 - y;
    const slope = dy / dx;
    let distRemaining = Math.sqrt(dx*dx + dy*dy);
    let dashIndex = 0, draw = true;
    while (distRemaining >= 0.1 && dashIndex < 10000) {
      let dashLength = dashArray[dashIndex++ % dashCount];
      if (dashLength === 0) dashLength = 0.001; // Safari hack
      if (dashLength > distRemaining) dashLength = distRemaining;
      const xStep = Math.sqrt(dashLength*dashLength / (1 + slope*slope));
      x += (dx < 0 ? -xStep : xStep);
      y += slope * (dx < 0 ? -xStep : xStep);
      this[draw ? 'lineTo' : 'moveTo'](x, y);
      distRemaining -= dashLength;
      draw = !draw;
    }
  };
}

箭頭幾何計算

function calcArrowhead(x, y, startX, startY) {
  const angle = Math.atan2(y - startY, x - startX) * 180 / Math.PI;
  const sideLen = 45, angleOffset = 35;
  return [
    x - sideLen * Math.cos((angle - angleOffset) * Math.PI/180),
    y - sideLen * Math.sin((angle - angleOffset) * Math.PI/180),
    x - sideLen * Math.cos((angle + angleOffset) * Math.PI/180),
    y - sideLen * Math.sin((angle + angleOffset) * Math.PI/180),
    angle
  ];
}

完整互動邏輯

const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
const startX = 350, startY = 350; // 固定起點
let targetX = 667, targetY = 470; // 初始終點

function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.lineWidth = +widthInput.value;
  ctx.lineCap = lineCapSelect.value;
  ctx.strokeStyle = 'rgb(0,0,100)';
  ctx.fillStyle = '#8BC54B';

  const dashPattern = dashInput.value.trim().split(/\s+/).map(Number);
  ctx.beginPath();
  // 依相對位置決定虛線方向
  if (targetX > startX) ctx.dashedLine(startX, startY, targetX, targetY, dashPattern);
  else ctx.dashedLine(targetX, targetY, startX, startY, dashPattern);

  // 畫箭頭
  const [ax1, ay1, ax2, ay2, ang] = calcArrowhead(targetX, targetY, startX, startY);
  ctx.moveTo(ax1, ay1);
  ctx.lineTo(targetX, targetY);
  ctx.lineTo(ax2, ay2);
  // 箭頭內凹連接點
  ctx.lineTo(
    targetX - 25 * Math.cos(ang * Math.PI/180),
    targetY - 25 * Math.sin(ang * Math.PI/180)
  );
  ctx.closePath();
  ctx.stroke();
  ctx.fill();
}

// UI 控制項綁定
widthInput.onkeyup = lineCapSelect.onchange = dashInput.onkeyup = draw;

// 滑鼠點擊更新終點
document.body.onmousedown = (e) => {
  const rect = canvas.getBoundingClientRect();
  targetX = (e.clientX || e.pageX) - rect.left;
  targetY = (e.clientY || e.pageY) - rect.top;
  draw();
};

draw(); // 初始化

UI 控制項

<label>線寬: <input id="widthInput" value="2" size="1"></label>
<label>虛線/間隙: <input id="dashInput" value="10 20" size="15"></label>
<label>線帽:
  <select id="lineCapSelect">
    <option>butt</option>
    <option selected>round</option>
    <option>square</option>
  </select></label>

應用場景

  • 工作流圖、流程圖連接線。
  • 地圖路徑規劃、向量場視覺化。
  • 教學示範幾何向量、物理受力圖。
copyright © 萬盛學電腦網 all rights reserved