js实现画图
使用Canvas API绘制图形
Canvas API是HTML5提供的原生绘图工具,通过JavaScript操作<canvas>元素实现2D图形绘制。基础步骤如下:
创建一个HTML文件并添加<canvas>元素:
<canvas id="myCanvas" width="500" height="500"></canvas>
JavaScript获取画布上下文并绘制图形:

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();
使用SVG动态生成矢量图形
通过JavaScript操作SVG DOM元素实现可缩放的矢量图形:
const svgNS = "http://www.w3.org/2000/svg";
const svg = document.createElementNS(svgNS, "svg");
svg.setAttribute('width', '500');
svg.setAttribute('height', '500');
document.body.appendChild(svg);
// 创建圆形
const circle = document.createElementNS(svgNS, "circle");
circle.setAttribute('cx', '100');
circle.setAttribute('cy', '100');
circle.setAttribute('r', '50');
circle.setAttribute('fill', 'green');
svg.appendChild(circle);
第三方库实现高级绘图
Chart.js(适合数据可视化):

import Chart from 'chart.js/auto';
const ctx = document.getElementById('chart').getContext('2d');
new Chart(ctx, {
type: 'bar',
data: {
labels: ['A', 'B', 'C'],
datasets: [{
label: 'Data',
data: [10, 20, 30],
backgroundColor: ['red', 'blue', 'yellow']
}]
}
});
p5.js(创意绘图):
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
ellipse(mouseX, mouseY, 80, 80);
}
实现交互式绘图板
结合鼠标事件实现简单绘图功能:
const canvas = document.getElementById('drawCanvas');
const ctx = canvas.getContext('2d');
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.strokeStyle = '#000';
ctx.lineWidth = 5;
ctx.stroke();
}
function stopDrawing() {
isDrawing = false;
}
WebGL实现3D绘图
通过Three.js简化WebGL操作:
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();






