js 实现画图
使用 Canvas API 绘制图形
Canvas API 是 JavaScript 中用于绘制图形的核心工具,适用于创建动态、交互式的图形内容。
初始化 Canvas
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
绘制矩形
ctx.fillStyle = 'blue';
ctx.fillRect(10, 10, 100, 50);
ctx.strokeStyle = 'red';
ctx.strokeRect(50, 50, 80, 30);
绘制圆形
ctx.beginPath();
ctx.arc(150, 150, 50, 0, Math.PI * 2);
ctx.fillStyle = 'green';
ctx.fill();
ctx.stroke();
使用 SVG 创建矢量图形
SVG 是基于 XML 的矢量图形格式,可直接嵌入 HTML 或通过 JavaScript 动态操作。
静态 SVG 示例
<svg width="200" height="200">
<circle cx="100" cy="100" r="50" fill="orange" />
</svg>
动态生成 SVG
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("width", "200");
svg.setAttribute("height", "200");
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", "purple");
svg.appendChild(circle);
document.body.appendChild(svg);
使用第三方库绘制图表
对于复杂图表需求,可借助专业库如 Chart.js 或 D3.js。
Chart.js 柱状图
new Chart(document.getElementById('chart'), {
type: 'bar',
data: {
labels: ['A', 'B', 'C'],
datasets: [{
label: 'Values',
data: [10, 20, 15],
backgroundColor: ['#ff6384', '#36a2eb', '#cc65fe']
}]
}
});
D3.js 折线图
const data = [10, 25, 15, 30, 20];
const svg = d3.select("body").append("svg")
.attr("width", 400)
.attr("height", 200);
const line = d3.line()
.x((d, i) => i * 50 + 20)
.y(d => 100 - d);
svg.append("path")
.datum(data)
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("d", line);
实现交互式绘图
通过事件监听实现画布交互功能。
鼠标绘图示例
let isDrawing = false;
canvas.addEventListener('mousedown', startDrawing);
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', stopDrawing);
function startDrawing(e) {
isDrawing = true;
ctx.beginPath();
ctx.moveTo(e.offsetX, e.offsetY);
}
function draw(e) {
if (!isDrawing) return;
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
}
function stopDrawing() {
isDrawing = false;
}
性能优化技巧
对于需要频繁更新的图形,采用以下策略提升性能。
离屏渲染
const offscreen = document.createElement('canvas');
const offCtx = offscreen.getContext('2d');
// 在离屏画布预渲染
offCtx.fillRect(0, 0, 100, 100);
// 主画布绘制时直接复制
ctx.drawImage(offscreen, 0, 0);
动画帧控制

function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制逻辑
}
animate();






