js 画图实现
JavaScript 画图实现方法
JavaScript 提供了多种方式实现图形绘制,包括原生 API 和第三方库。以下是常见方法:
使用 Canvas API
HTML5 Canvas 是浏览器原生支持的 2D 绘图 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, 60, 50, 0, Math.PI * 2);
ctx.fillStyle = 'blue';
ctx.fill();
使用 SVG
SVG 是矢量图形标准,可通过 DOM 操作动态修改。
// 创建 SVG 元素
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("width", "300");
svg.setAttribute("height", "200");
// 添加圆形
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", "green");
svg.appendChild(circle);
// 添加到页面
document.body.appendChild(svg);
使用 WebGL
WebGL 提供 3D 图形渲染能力,基于 OpenGL ES 标准。
// 初始化 WebGL
const canvas = document.getElementById('glCanvas');
const gl = canvas.getContext('webgl');
// 设置清除颜色和清除
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);
使用第三方库
-
D3.js - 数据可视化库
d3.select("body").append("svg") .attr("width", 500) .attr("height", 500) .append("circle") .attr("cx", 250) .attr("cy", 250) .attr("r", 50) .attr("fill", "purple"); -
Three.js - 3D 图形库
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); -
Chart.js - 图表库
new Chart(document.getElementById('myChart'), { type: 'bar', data: { labels: ['Red', 'Blue', 'Yellow'], datasets: [{ label: 'Colors', data: [10, 20, 30] }] } });
性能优化建议
- 对于频繁更新的图形,使用 Canvas 比 SVG 更高效
- 复杂动画考虑使用 requestAnimationFrame
- 大量图形元素时使用对象池技术
- WebGL 应用注意减少 draw call 次数
选择具体技术时需考虑项目需求:

- 简单静态图形:SVG
- 动态2D内容:Canvas
- 3D渲染:WebGL/Three.js
- 数据可视化:D3.js/Chart.js






