js实现画图
使用 Canvas API 绘制图形
Canvas API 是 HTML5 提供的原生绘图工具,通过 JavaScript 直接操作像素绘制图形。
<canvas id="myCanvas" width="500" height="500"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 绘制矩形
ctx.fillStyle = 'blue';
ctx.fillRect(50, 50, 100, 100);
// 绘制圆形
ctx.beginPath();
ctx.arc(200, 200, 50, 0, Math.PI * 2);
ctx.fillStyle = 'red';
ctx.fill();
</script>
使用 SVG 动态创建矢量图形
SVG 是 XML 格式的矢量图形,可通过 JavaScript 动态创建和修改。
<svg id="mySvg" width="500" height="500"></svg>
<script>
const svg = document.getElementById('mySvg');
// 创建矩形
const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
rect.setAttribute('x', 50);
rect.setAttribute('y', 50);
rect.setAttribute('width', 100);
rect.setAttribute('height', 100);
rect.setAttribute('fill', 'green');
svg.appendChild(rect);
// 创建圆形
const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
circle.setAttribute('cx', 200);
circle.setAttribute('cy', 200);
circle.setAttribute('r', 50);
circle.setAttribute('fill', 'yellow');
svg.appendChild(circle);
</script>
使用第三方库绘制复杂图形
D3.js 和 Chart.js 等库简化了复杂图形的创建过程。
<canvas id="myChart" width="500" height="500"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow'],
datasets: [{
label: 'Colors',
data: [12, 19, 3],
backgroundColor: ['red', 'blue', 'yellow']
}]
}
});
</script>
实现绘图板功能
结合鼠标事件可以实现简单的绘图板功能。
<canvas id="drawingBoard" width="500" height="500" style="border:1px solid #000;"></canvas>
<script>
const canvas = document.getElementById('drawingBoard');
const ctx = canvas.getContext('2d');
let isDrawing = false;
canvas.addEventListener('mousedown', () => isDrawing = true);
canvas.addEventListener('mouseup', () => isDrawing = false);
canvas.addEventListener('mousemove', (e) => {
if (!isDrawing) return;
ctx.fillStyle = 'black';
ctx.fillRect(e.offsetX, e.offsetY, 5, 5);
});
</script>
绘制动画效果
通过 requestAnimationFrame 实现平滑动画。

<canvas id="animationCanvas" width="500" height="500"></canvas>
<script>
const canvas = document.getElementById('animationCanvas');
const ctx = canvas.getContext('2d');
let x = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'purple';
ctx.fillRect(x, 100, 50, 50);
x = (x + 2) % canvas.width;
requestAnimationFrame(animate);
}
animate();
</script>






