無 Canvas、無 SVG,純 <span> 元素模擬像素點,通過數學算法繪製點、線、折線、多邊形、矩形。雖非生產級方案,但極佳展示幾何算法與 DOM 操作結合的思維。
<span style="position:absolute; width:1px; height:1px; background:red"
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;
}
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);
}
// 折線:連續線段
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);
}
}
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 2D | SVG |
|---|---|---|---|
| 1000 點渲染 | ~50ms (DOM 開銷大) | <1ms | ~5ms |
| 10000 點 | 卡頓/崩潰 | ~5ms | ~50ms |
| 事件綁定 | 原生支持 | 需座標轉換 | 原生支持 |
| 縮放清晰度 | 模糊 (像素放大) | 模糊 | 矢量無損 |
| 動畫性能 | 極差 | 優 (requestAnimationFrame) | 中等 |
生產環境請使用 Canvas 2D / WebGL / SVG / CSS,此純 DOM 方案僅供算法教學與極簡場景。