js实现画线
使用Canvas API画线
Canvas API是HTML5提供的绘图接口,适用于动态生成图形。在JavaScript中通过获取Canvas元素的上下文进行绘制。
// 获取Canvas元素和上下文
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 设置线条样式
ctx.strokeStyle = 'red';
ctx.lineWidth = 5;
// 开始绘制路径
ctx.beginPath();
ctx.moveTo(50, 50); // 起点坐标
ctx.lineTo(200, 100); // 终点坐标
ctx.stroke(); // 描边路径
使用SVG画线
SVG是矢量图形标准,可通过DOM操作动态创建线条元素。

// 创建SVG元素
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute('width', '300');
svg.setAttribute('height', '150');
// 创建线条元素
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', '100');
line.setAttribute('stroke', 'blue');
line.setAttribute('stroke-width', '3');
// 添加到DOM
svg.appendChild(line);
document.body.appendChild(svg);
使用CSS画线
通过CSS伪元素或边框属性创建简单线条,适合静态场景。

<style>
.line {
position: relative;
height: 1px;
background: black;
width: 200px;
transform: rotate(30deg);
}
</style>
<div class="line"></div>
使用WebGL画线
WebGL提供高性能3D/2D渲染能力,适合复杂图形需求。
const canvas = document.getElementById('glCanvas');
const gl = canvas.getContext('webgl');
// 顶点着色器
const vsSource = `
attribute vec2 position;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
}`;
// 片段着色器
const fsSource = `
void main() {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}`;
// 初始化着色器程序
const shaderProgram = initShaderProgram(gl, vsSource, fsSource);
const positions = new Float32Array([-0.5, -0.5, 0.5, 0.5]);
// 创建缓冲区
const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
gl.bufferData(gl.ARRAY_BUFFER, positions, gl.STATIC_DRAW);
// 绘制线条
gl.drawArrays(gl.LINES, 0, 2);
使用第三方库画线
常见图形库如D3.js、Paper.js等提供更高级的绘图功能。
// 使用Paper.js示例
paper.install(window);
window.onload = function() {
paper.setup('myCanvas');
const path = new Path.Line({
from: [100, 100],
to: [300, 150],
strokeColor: 'green',
strokeWidth: 4
});
paper.view.draw();
};
性能优化建议
- 批量绘制:在Canvas中尽量减少beginPath/stroke的调用次数
- 离屏渲染:复杂图形可先在隐藏Canvas中绘制后复制
- 分辨率适配:根据设备像素比调整Canvas尺寸避免模糊
- 动画优化:使用requestAnimationFrame实现流畅动画
各方法选择取决于具体需求:Canvas适合动态图形,SVG适合可交互图形,WebGL适合高性能场景,CSS适合简单装饰性线条。






