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(200, 200); // 终点坐标
ctx.stroke(); // 绘制线条
使用 SVG 画线
SVG 是矢量图形标准,可以通过 HTML 直接嵌入或动态创建。

// 创建 SVG 元素
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('width', '300');
svg.setAttribute('height', '300');
// 创建线条元素
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', '250');
line.setAttribute('stroke', 'red');
line.setAttribute('stroke-width', '3');
// 添加到文档
svg.appendChild(line);
document.body.appendChild(svg);
使用 CSS 和 DOM 画线
通过 CSS 样式和 DOM 元素模拟线条效果。
// 创建 div 元素作为线条
const line = document.createElement('div');
line.style.position = 'absolute';
line.style.width = '200px';
line.style.height = '2px';
line.style.backgroundColor = 'green';
line.style.left = '50px';
line.style.top = '100px';
line.style.transform = 'rotate(45deg)';
line.style.transformOrigin = '0 0';
// 添加到文档
document.body.appendChild(line);
使用第三方库画线
使用如 D3.js 或 Paper.js 等图形库可以简化绘图过程。

// 使用 D3.js 画线
const svg = d3.select('body').append('svg')
.attr('width', 300)
.attr('height', 300);
svg.append('line')
.attr('x1', 50)
.attr('y1', 50)
.attr('x2', 250)
.attr('y2', 250)
.attr('stroke', 'purple')
.attr('stroke-width', 4);
动画线条绘制
通过 Canvas 实现动画效果的线条绘制。
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
let progress = 0;
function drawAnimatedLine() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(50 + progress * 2, 50 + progress);
ctx.stroke();
progress += 1;
if (progress <= 100) {
requestAnimationFrame(drawAnimatedLine);
}
}
drawAnimatedLine();
响应式线条绘制
根据用户输入动态绘制线条。
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
let isDrawing = false;
let startX, startY;
canvas.addEventListener('mousedown', (e) => {
isDrawing = true;
startX = e.offsetX;
startY = e.offsetY;
});
canvas.addEventListener('mousemove', (e) => {
if (!isDrawing) return;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.moveTo(startX, startY);
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
});
canvas.addEventListener('mouseup', () => {
isDrawing = false;
});
以上方法覆盖了从原生 API 到第三方库的多种实现方式,可根据具体需求选择适合的方案。






