js实现绘图
使用Canvas API绘制图形
Canvas API是HTML5提供的绘图工具,通过JavaScript操作<canvas>元素实现动态绘图。基本步骤如下:
-
在HTML中添加
<canvas>元素<canvas id="myCanvas" width="500" height="500"></canvas> -
获取Canvas上下文并绘制图形
const canvas = document.getElementById('myCanvas'); const ctx = canvas.getContext('2d');
// 绘制矩形 ctx.fillStyle = 'blue'; ctx.fillRect(50, 50, 100, 100);

// 绘制圆形 ctx.beginPath(); ctx.arc(250, 250, 50, 0, Math.PI * 2); ctx.fillStyle = 'red'; ctx.fill();
### 使用SVG实现矢量绘图
SVG是基于XML的矢量图形格式,可以通过JavaScript动态创建和修改:
```javascript
// 创建SVG元素
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("width", "500");
svg.setAttribute("height", "500");
document.body.appendChild(svg);
// 添加圆形
const circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
circle.setAttribute("cx", "100");
circle.setAttribute("cy", "100");
circle.setAttribute("r", "50");
circle.setAttribute("fill", "green");
svg.appendChild(circle);
使用第三方库绘制图表
对于复杂图表,推荐使用成熟的JavaScript库:
-
Chart.js - 简单易用的图表库

new Chart(document.getElementById('chart'), { type: 'bar', data: { labels: ['A', 'B', 'C'], datasets: [{ label: '数据集', data: [10, 20, 30] }] } }); -
D3.js - 强大的数据可视化库
d3.select("body") .selectAll("div") .data([4, 8, 15, 16, 23, 42]) .enter() .append("div") .style("height", d => d * 10 + "px");
实现动画效果
通过requestAnimationFrame实现平滑动画:
function animate() {
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 更新位置
x += dx;
y += dy;
// 绘制
ctx.beginPath();
ctx.arc(x, y, 20, 0, Math.PI*2);
ctx.fillStyle = 'orange';
ctx.fill();
requestAnimationFrame(animate);
}
let x = 50, y = 50, dx = 2, dy = 1;
animate();
响应式绘图处理
确保绘图在不同屏幕尺寸下正常显示:
function resizeCanvas() {
const canvas = document.getElementById('myCanvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 重绘内容
drawContent();
}
window.addEventListener('resize', resizeCanvas);
resizeCanvas();






