js 实现画图
在JavaScript中实现画图可以通过多种方式,以下是几种常见的方法:
使用HTML5 Canvas
Canvas是HTML5提供的绘图API,适合动态图形和游戏开发。
// 获取Canvas元素
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 绘制矩形
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 100, 100);
// 绘制圆形
ctx.beginPath();
ctx.arc(200, 75, 50, 0, 2 * Math.PI);
ctx.fillStyle = 'blue';
ctx.fill();
使用SVG
SVG是基于XML的矢量图形技术,适合需要缩放的高质量图形。
// 创建SVG元素
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('width', '300');
svg.setAttribute('height', '200');
// 添加矩形
const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
rect.setAttribute('x', '10');
rect.setAttribute('y', '10');
rect.setAttribute('width', '100');
rect.setAttribute('height', '100');
rect.setAttribute('fill', 'green');
svg.appendChild(rect);
// 添加到DOM
document.body.appendChild(svg);
使用第三方库
对于复杂图形或图表,可以使用如D3.js、Chart.js等库。
// 使用Chart.js绘制柱状图
const ctx = document.getElementById('chart').getContext('2d');
new Chart(ctx, {
type: 'bar',
data: {
labels: ['A', 'B', 'C'],
datasets: [{
label: 'Values',
data: [10, 20, 30],
backgroundColor: ['red', 'blue', 'green']
}]
}
});
使用CSS绘制简单图形
CSS也能绘制基础图形,适合静态元素。

<style>
.circle {
width: 100px;
height: 100px;
border-radius: 50%;
background-color: purple;
}
</style>
<div class="circle"></div>
选择建议
- Canvas:适合像素操作、动画和游戏。
- SVG:适合矢量图形和需要交互的场景。
- 第三方库:简化复杂图表开发。
- CSS:适合静态简单图形。
根据需求选择合适的技术组合。






