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 = 'red';
ctx.fillRect(50, 50, 100, 100); // 绘制红色矩形
</script>
绘制复杂路径
Canvas支持自定义路径绘制,以下代码绘制一个三角形:
ctx.beginPath();
ctx.moveTo(100, 100);
ctx.lineTo(200, 100);
ctx.lineTo(150, 50);
ctx.closePath();
ctx.stroke();
使用SVG绘图
通过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", "blue");
svg.appendChild(circle);
第三方绘图库
使用开源库如Chart.js绘制数据图表:
import Chart from 'chart.js/auto';
new Chart(document.getElementById('chart'), {
type: 'bar',
data: {
labels: ['A', 'B', 'C'],
datasets: [{ data: [10, 20, 30] }]
}
});
动画实现
结合requestAnimationFrame实现Canvas动画:

let x = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(x, 50, 50, 50);
x += 2;
requestAnimationFrame(animate);
}
animate();
交互式绘图
监听鼠标事件实现交互绘图:
canvas.addEventListener('mousemove', (e) => {
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
ctx.fillRect(x, y, 10, 10);
});
WebGL高级绘图
使用Three.js进行3D绘图:
import * as THREE from 'three';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
function animate() {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();






