js实现画线
使用 Canvas API 绘制线条
Canvas API 是 HTML5 提供的绘图接口,通过 JavaScript 可以直接在画布上绘制线条。

// 获取 Canvas 元素和上下文
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 设置线条样式
ctx.strokeStyle = 'blue';
ctx.lineWidth = 5;
// 开始绘制路径
ctx.beginPath();
ctx.moveTo(50, 50); // 起点坐标
ctx.lineTo(250, 50); // 终点坐标
ctx.stroke(); // 绘制线条
使用 SVG 绘制线条
SVG 是矢量图形标准,可以通过 HTML 直接嵌入或动态创建。

// 创建 SVG 元素
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("width", "300");
svg.setAttribute("height", "100");
// 创建线条元素
const line = document.createElementNS("http://www.w3.org/2000/svg", "line");
line.setAttribute("x1", "50");
line.setAttribute("y1", "50");
line.setAttribute("x2", "250");
line.setAttribute("y2", "50");
line.setAttribute("stroke", "red");
line.setAttribute("stroke-width", "5");
// 添加到 DOM
svg.appendChild(line);
document.body.appendChild(svg);
使用 CSS 和 HTML 元素模拟线条
通过绝对定位的 div 元素和 CSS 变换可以模拟线条效果。
// 创建线条元素
const line = document.createElement('div');
line.style.position = 'absolute';
line.style.backgroundColor = 'green';
line.style.height = '3px';
line.style.width = '200px';
line.style.left = '50px';
line.style.top = '50px';
line.style.transformOrigin = '0 0';
line.style.transform = 'rotate(0deg)'; // 可调整角度
// 添加到页面
document.body.appendChild(line);
使用第三方库(如 D3.js)
D3.js 提供了更高级的图形绘制功能,适合复杂可视化需求。
// 使用 D3.js 绘制线条
d3.select("body")
.append("svg")
.attr("width", 300)
.attr("height", 100)
.append("line")
.attr("x1", 50)
.attr("y1", 50)
.attr("x2", 250)
.attr("y2", 50)
.attr("stroke", "purple")
.attr("stroke-width", 5);
性能优化建议
对于需要频繁绘制或动态更新的线条,Canvas 通常比 SVG 性能更好。静态图形或需要 DOM 交互的场景,SVG 更合适。动画场景可考虑使用 CSS 变换或 requestAnimationFrame 进行优化。






