js实现画图
JavaScript 画图基础方法
使用 HTML5 的 <canvas> 元素是实现画图的核心方式。通过获取画布上下文,可以绘制线条、形状、文本等。
// 获取画布和上下文
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 绘制矩形
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 100, 100);
绘制路径
路径绘制适用于复杂图形,通过 beginPath() 和 stroke()/fill() 控制。
ctx.beginPath();
ctx.moveTo(50, 50); // 起点
ctx.lineTo(150, 50); // 直线
ctx.arc(100, 100, 50, 0, Math.PI * 2); // 圆
ctx.stroke(); // 描边
使用第三方库
对于高级绘图需求,可引入库如 Chart.js(数据可视化)或 Fabric.js(交互式绘图)。
Chart.js 示例:
new Chart(document.getElementById('chart'), {
type: 'bar',
data: {
labels: ['A', 'B', 'C'],
datasets: [{
data: [10, 20, 30],
backgroundColor: ['#ff0000', '#00ff00', '#0000ff']
}]
}
});
SVG 绘图替代方案
通过操作 SVG DOM 实现矢量图形,适合可缩放图形。
const svg = document.getElementById('svgCanvas');
const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
circle.setAttribute('cx', '50');
circle.setAttribute('cy', '50');
circle.setAttribute('r', '40');
circle.setAttribute('fill', 'blue');
svg.appendChild(circle);
动画实现
结合 requestAnimationFrame 实现动态效果。
let x = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(x, 50, 20, 20);
x += 2;
requestAnimationFrame(animate);
}
animate();
事件交互
监听鼠标事件实现交互式绘图。
canvas.addEventListener('mousemove', (e) => {
const rect = canvas.getBoundingClientRect();
ctx.fillRect(e.clientX - rect.left, e.clientY - rect.top, 5, 5);
});






