萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

原生 JavaScript 繪製幾何圖形:點、線、面、多邊形完整實現

原生 JS 繪圖引擎:從像素點到多邊形的純 DOM 實現

無 Canvas、無 SVG,純 <span> 元素模擬像素點,通過數學算法繪製點、線、折線、多邊形、矩形。雖非生產級方案,但極佳展示幾何算法與 DOM 操作結合的思維。

核心原理:點陣模擬

  • 每個「像素」是一個 <span style="position:absolute; width:1px; height:1px; background:red"
  • 直線 = 兩點間等距離排列的點集 (Bresenham 算法簡化版)
  • 折線/多邊形 = 多條線段首尾相連
  • 填充 = 掃描線算法或疊加矩形

1. 繪製單點


function drawPoint(opts) {
  const { x, y, size = 1, color = 'DarkRed', label } = opts;
  const span = document.createElement('span');
  span.style.cssText = `
    display: inline-block; position: absolute;
    left: ${x}px; top: ${y}px;
    width: ${size}px; height: ${size}px;
    background-color: ${color};
    pointer-events: none;
  `;
  if (label) {
    span.innerHTML = `
${label}
`; } document.body.appendChild(span); return span; }

2. 繪製直線 (改進版 Bresenham)


function drawLine(x1, y1, x2, y2, options = {}) {
  const { color = 'DarkRed', pointSize = 1 } = options;
  const dx = Math.abs(x2 - x1);
  const dy = Math.abs(y2 - y1);
  const sx = x1 < x2 ? 1 : -1;
  const sy = y1 < y2 ? 1 : -1;
  let err = dx - dy;
  
  const points = [];
  while (true) {
    points.push([x1, y1]);
    if (x1 === x2 && y1 === y2) break;
    const e2 = 2 * err;
    if (e2 > -dy) { err -= dy; x1 += sx; }
    if (e2 < dx) { err += dx; y1 += sy; }
  }
  
  // 批量創建 DOM (DocumentFragment 優化)
  const frag = document.createDocumentFragment();
  points.forEach(([x, y]) => {
    const s = document.createElement('span');
    s.style.cssText = `position:absolute;left:${x}px;top:${y}px;width:${pointSize}px;height:${pointSize}px;background:${color}`;
    frag.appendChild(s);
  });
  document.body.appendChild(frag);
}

3. 折線與多邊形


// 折線:連續線段
function drawPolyline(points, options) {
  for (let i = 0; i < points.length - 1; i++) {
    drawLine(points[i][0], points[i][1], points[i+1][0], points[i+1][1], options);
  }
  // 繪製轉折點
  points.forEach(([x, y]) => drawPoint({ x, y, size: 3, color: 'red' }));
}

// 多邊形:閉合折線
function drawPolygon(points, options) {
  drawPolyline(points, options);
  if (points.length > 2) {
    const last = points[points.length - 1];
    const first = points[0];
    drawLine(last[0], last[1], first[0], first[1], options);
  }
}

4. 矩形 (優化:單元素而非點陣)


function drawRect(x, y, width, height, options = {}) {
  const { color = 'Green', border = '1px solid #000', fill = true } = options;
  const div = document.createElement('div');
  div.style.cssText = `
    position: absolute; left: ${x}px; top: ${y}px;
    width: ${width}px; height: ${height}px;
    box-sizing: border-box; border: ${border};
    ${fill ? `background-color: ${color};` : ''}
  `;
  document.body.appendChild(div);
  return div;
}

完整演示頁面


<html>
<body style="height:100vh;position:relative;">
<script>
// 測試
drawPoint({ x: 100, y: 100, label: '原點' });
drawLine(100, 100, 300, 200, { color: 'blue' });
drawPolyline([[300,200], [400,150], [500,250]], { color: 'green' });
drawPolygon([[100,300], [200,250], [250,350], [150,380]], { color: 'purple' });
drawRect(400, 300, 100, 80, { color: 'orange', border: '2px dashed red' });
</script>
</body>
</html>

性能與局限性分析

指標DOM 點陣Canvas 2DSVG
1000 點渲染~50ms (DOM 開銷大)<1ms~5ms
10000 點卡頓/崩潰~5ms~50ms
事件綁定原生支持需座標轉換原生支持
縮放清晰度模糊 (像素放大)模糊矢量無損
動畫性能極差優 (requestAnimationFrame)中等

教學價值總結

  • 理解光柵化核心:幾何圖形 → 離散像素點
  • 掌握 Bresenham 畫線算法 精髓:整數運算、誤差累積判斷
  • 體會 DocumentFragment 批量 DOM 操作的必要性
  • 認清 DOM 做圖形的邊界:僅適合極簡裝飾、教學演示

生產環境請使用 Canvas 2D / WebGL / SVG / CSS,此純 DOM 方案僅供算法教學與極簡場景。

copyright © 萬盛學電腦網 all rights reserved