js实现绘图
JavaScript 绘图基础
使用 JavaScript 绘图可以通过多种方式实现,包括原生 Canvas API、第三方库(如 D3.js、Chart.js)以及 SVG 操作。以下是几种常见方法:
Canvas API 绘图
Canvas 是 HTML5 提供的原生绘图 API,适合像素级操作和动态图形:
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 绘制矩形
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 100, 50);
// 绘制路径
ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(150, 150);
ctx.stroke();
// 绘制圆形
ctx.beginPath();
ctx.arc(100, 100, 30, 0, Math.PI * 2);
ctx.fillStyle = 'blue';
ctx.fill();
SVG 绘图
SVG 是矢量图形标准,可通过 DOM 操作:
<svg width="200" height="200">
<circle cx="100" cy="100" r="40" fill="green" />
<rect x="50" y="50" width="100" height="60" fill="yellow" />
</svg>
使用第三方库
Chart.js(适合数据可视化):
new Chart(document.getElementById('chart'), {
type: 'bar',
data: {
labels: ['A', 'B', 'C'],
datasets: [{
label: 'Values',
data: [10, 20, 30],
backgroundColor: ['red', 'blue', 'green']
}]
}
});
D3.js(适合复杂交互式图表):
d3.select('body')
.append('svg')
.selectAll('circle')
.data([10, 20, 30])
.enter()
.append('circle')
.attr('cx', (d, i) => i * 50 + 30)
.attr('cy', 50)
.attr('r', d => d);
动画实现
Canvas 动画示例:
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 更新并绘制对象
x += speed;
ctx.fillRect(x, 50, 20, 20);
}
animate();
性能优化建议
- 对于静态图形优先使用 SVG
- 复杂动画使用 Canvas 并合理限制绘制区域
- 使用
requestAnimationFrame替代setTimeout实现动画 - 离屏 Canvas 预渲染复杂图形
浏览器兼容性
现代浏览器均支持 Canvas 和 SVG,如需兼容旧版 IE(9以下),需引入 polyfill 或降级方案。







