Skip to content

图形与动画:Canvas / WebGL / Three.js ​

DOM 是给"文档"设计的,几千个元素就开始卡。要画游戏 / 数据可视化 / 3D / 海量元素,要用底层图形 API:

SVG       矢量,DOM 一份子,适合 < 几百个元素的图表
Canvas 2D 像素 API,画到位图,几千~几万元素流畅
WebGL    GPU 着色器编程,几百万元素 / 3D
WebGPU   2024 新一代 GPU API,比 WebGL 强且现代
Three.js 基于 WebGL 的 3D 高级库

这一篇按"低到高"讲清楚。


一、何时用什么 ​

任务                            技术
图标 / Logo                     SVG
柱状图 / 折线图(< 100 数据)    SVG(D3)
柱状图 / 折线图(> 1000 数据)   Canvas(ECharts / Chart.js)
小游戏 2D                       Canvas
画板 / 白板                     Canvas
真实 3D 场景 / VR               WebGL / Three.js
高级 GPU 计算                   WebGPU
数据可视化(GIS / 散点万级)    WebGL(deck.gl / Mapbox)

先看需求:能用 SVG 别用 Canvas,能用 Canvas 别用 WebGL。复杂度递增。


二、SVG:矢量图标 + 简单图表 ​

html
<svg width="200" height="200" viewBox="0 0 200 200">
  <rect x="10" y="10" width="50" height="50" fill="blue" />
  <circle cx="100" cy="100" r="40" fill="red" />
  <path d="M 10 10 L 200 200" stroke="black" stroke-width="2" />
  <text x="50" y="50" font-size="20">Hello</text>
</svg>

优点:

  • 矢量,任意缩放清晰
  • 是 DOM,可以用 CSS 设样式 + JS 绑事件
  • 易做交互(hover、点击)
  • 可访问性好(屏幕阅读器能读)

缺点:元素多了卡。1000 个 <circle> 可能卡顿,10000 个肯定挂。

库 ​

D3.js          数据可视化基础(底层)
Recharts       React 图表
Chart.js       SVG/Canvas 都支持
Visx           D3 + React 封装

三、Canvas 2D ​

1. 基础 ​

html
<canvas id="c" width="800" height="600"></canvas>
js
const c = document.getElementById('c');
const ctx = c.getContext('2d');

// 矩形
ctx.fillStyle = 'blue';
ctx.fillRect(10, 10, 100, 100);

// 圆
ctx.beginPath();
ctx.arc(200, 100, 50, 0, Math.PI * 2);
ctx.fillStyle = 'red';
ctx.fill();

// 路径
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(800, 600);
ctx.strokeStyle = 'black';
ctx.lineWidth = 2;
ctx.stroke();

// 文字
ctx.font = '20px Arial';
ctx.fillStyle = 'black';
ctx.fillText('Hello', 50, 50);

// 图片
const img = new Image();
img.src = '/photo.jpg';
img.onload = () => ctx.drawImage(img, 0, 0);

Canvas 是位图,画完就是像素,不能选中 / 不能事件。要交互需自己计算"鼠标是否在某图形上"。

2. 高 DPI 屏 ​

js
const dpr = window.devicePixelRatio || 1;
c.width = 800 * dpr;
c.height = 600 * dpr;
c.style.width = '800px';
c.style.height = '600px';
ctx.scale(dpr, dpr);

不处理 DPR,Retina 屏看着模糊。

3. 动画循环 ​

js
function loop() {
  ctx.clearRect(0, 0, 800, 600);   // 清空
  // 画
  ctx.fillRect(x, 100, 50, 50);
  x += 1;

  requestAnimationFrame(loop);
}
loop();

每帧清屏 + 重画。简单但全部重绘可能慢,可以"只重画变化区域"(脏矩形)。

4. 检测点击 ​

js
c.addEventListener('click', (e) => {
  const rect = c.getBoundingClientRect();
  const x = e.clientX - rect.left;
  const y = e.clientY - rect.top;

  // 检查 (x, y) 是否在某图形里
  for (const shape of shapes) {
    if (isPointInShape(x, y, shape)) {
      console.log('clicked', shape);
    }
  }
});

或用 Canvas 自己的 isPointInPath:

js
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2);
if (ctx.isPointInPath(x, y)) { /* 命中 */ }

5. 离屏 Canvas ​

js
const off = document.createElement('canvas');
off.width = 200; off.height = 200;
const offCtx = off.getContext('2d');
// 在离屏画
offCtx.fillRect(...);

// 一次性贴到主 Canvas
ctx.drawImage(off, 100, 100);

性能优化:复杂图形画一次到离屏,主 canvas 直接 drawImage(不重新算)。

OffscreenCanvas + Web Worker:

js
const off = new OffscreenCanvas(800, 600);
const worker = new Worker('./paint.js');
worker.postMessage({ canvas: off }, [off]);
// Worker 里画,主线程不卡

6. Canvas 库 ​

Konva.js     2D 场景图(像 Three.js 的 2D 版),适合白板 / 编辑器
PixiJS        2D 游戏引擎,WebGL 加速
Fabric.js    SVG-like API on Canvas,白板
ECharts       图表(底层用 zrender,Canvas + SVG)

四、WebGL:GPU 编程 ​

1. 概念 ​

CPU(JS)发指令给 GPU
GPU 跑 vertex shader → 算每个顶点位置
GPU 跑 fragment shader → 算每个像素颜色
GPU 输出到屏幕

关键概念:
  Vertex(顶点)        三角形的角
  Fragment(片元)      最终像素的候选
  Shader              GPU 上跑的小程序(GLSL 语言)
  Buffer              CPU 传给 GPU 的数据
  Texture             GPU 上的图片

2. Hello Triangle ​

js
const gl = canvas.getContext('webgl2');

// 顶点着色器(GLSL)
const vsSource = `#version 300 es
  in vec2 position;
  void main() { gl_Position = vec4(position, 0.0, 1.0); }
`;

// 片元着色器
const fsSource = `#version 300 es
  precision highp float;
  out vec4 fragColor;
  void main() { fragColor = vec4(1.0, 0.0, 0.0, 1.0); }
`;

// 编译 + 链接 shader,创建 program
// ... (省略 50 行模板代码)

// 顶点数据
const vertices = new Float32Array([
  0.0, 0.5,
  -0.5, -0.5,
  0.5, -0.5,
]);

// 上传到 GPU
const buf = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buf);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);

// 画
gl.drawArrays(gl.TRIANGLES, 0, 3);

WebGL 直接写非常啰嗦,几十行才能画三角形。几乎没人裸写 WebGL,都用 Three.js / regl / twgl 等库。

3. WebGL 适合什么 ​

  • 3D 渲染:游戏、VR、产品展示
  • 大规模数据可视化:百万散点、地图、粒子
  • 图像处理:滤镜(GPU 比 CPU 快几十倍)
  • 物理模拟:粒子系统、流体

五、Three.js:3D 主流方案 ​

bash
pnpm add three
pnpm add -D @types/three

1. Hello 立方体 ​

ts
import * as THREE from 'three';

// 场景 + 相机 + 渲染器
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, innerWidth / innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);

// 立方体
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshStandardMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

// 灯光
const light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(5, 5, 5);
scene.add(light);
scene.add(new THREE.AmbientLight(0x404040));

camera.position.z = 5;

// 动画
function animate() {
  cube.rotation.x += 0.01;
  cube.rotation.y += 0.01;
  renderer.render(scene, camera);
  requestAnimationFrame(animate);
}
animate();

2. 关键概念 ​

Scene       场景(容器)
Camera      相机(视角)
  PerspectiveCamera     透视(真实)
  OrthographicCamera    正交(工程)
Renderer    渲染器
Mesh        网格 = Geometry + Material
Geometry    几何形状(顶点数据)
  BoxGeometry / SphereGeometry / PlaneGeometry / 自定义
Material    材质(颜色 / 贴图 / 反射 / ...)
  MeshBasicMaterial     不受光
  MeshStandardMaterial  PBR 标准
Light       光
  Directional / Point / Spot / Ambient
Texture     贴图(图片/视频)
Loader      模型加载(GLTF / OBJ / FBX)
Raycaster   射线检测(点击 3D 物体)
Controls    相机控制(OrbitControls / FlyControls)

3. 加载模型 ​

ts
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';

const loader = new GLTFLoader();
loader.load('/model.glb', (gltf) => {
  scene.add(gltf.scene);
});

GLTF / GLB 是 3D 文件标准,类似 3D 界的 JSON。Blender / Maya 都能导出。

4. 交互 ​

ts
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';

const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
ts
// 射线检测点击
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();

window.addEventListener('click', (e) => {
  mouse.x = (e.clientX / innerWidth) * 2 - 1;
  mouse.y = -(e.clientY / innerHeight) * 2 + 1;
  raycaster.setFromCamera(mouse, camera);

  const hits = raycaster.intersectObjects(scene.children);
  if (hits[0]) console.log('clicked', hits[0].object);
});

5. React Three Fiber(声明式) ​

bash
pnpm add three @react-three/fiber @react-three/drei
tsx
import { Canvas } from '@react-three/fiber';
import { OrbitControls } from '@react-three/drei';

function Cube() {
  const ref = useRef();
  useFrame(() => { ref.current.rotation.y += 0.01; });
  return (
    <mesh ref={ref}>
      <boxGeometry args={[1, 1, 1]} />
      <meshStandardMaterial color="green" />
    </mesh>
  );
}

function App() {
  return (
    <Canvas>
      <ambientLight />
      <directionalLight position={[5, 5, 5]} />
      <Cube />
      <OrbitControls />
    </Canvas>
  );
}

像写 React 一样写 3D。强烈推荐 React 项目用 R3F + drei。

6. 性能 ​

< 100k 三角形           随便写
100k ~ 1M 三角形         注意 draw call 数量(每物体一次 draw call)
> 1M                    用 InstancedMesh / merge geometry

优化:

  • Instanced Mesh:同一物体多个实例,一次 draw call
  • LOD(Level of Detail):远处用低模
  • Frustum culling:相机看不到的不画
  • 压缩贴图 / KTX2

六、WebGPU:下一代 ​

WebGL 基于 OpenGL ES,API 老旧。WebGPU(Chrome 113+ 默认开)是 2024 新标准,基于 Vulkan / Metal / DX12,API 现代 + 性能更好 + 支持计算。

ts
const adapter = await navigator.gpu.requestAdapter();
const device = await adapter.requestDevice();
// ... 写 WGSL shader,流程跟 WebGL 类似但 API 更清晰

特点:

  • WGSL shader 语言(类似 Rust 语法)
  • Compute Shader:GPU 通用计算(机器学习 / 模拟)
  • 性能比 WebGL 好 10-30%
  • API 更现代

兼容性:Chrome / Edge ✅,Firefox / Safari 跟进中(Safari 18 部分支持)。

Three.js / Babylon.js 都在加 WebGPU 后端。普通开发者不用学底层 API,通过库享受性能提升。


七、动画库 ​

DOM 动画其实大头不在 Canvas / WebGL,而是普通 UI 动效。主流:

1. CSS 动画(简单) ​

css
.box { transition: transform 0.3s; }
.box:hover { transform: scale(1.1); }

@keyframes fade { from { opacity: 0; } to { opacity: 1; } }

2. Framer Motion(React 主流) ​

tsx
import { motion } from 'framer-motion';

<motion.div
  initial={{ opacity: 0, y: 20 }}
  animate={{ opacity: 1, y: 0 }}
  exit={{ opacity: 0 }}
  transition={{ duration: 0.3 }}
>
  Hello
</motion.div>

物理动画 / 手势 / 进入退出动画一站式。React 项目首选。

3. GSAP(老牌强大) ​

ts
import gsap from 'gsap';

gsap.to('.box', { x: 100, rotation: 360, duration: 1 });
gsap.from('.fade-in', { opacity: 0, y: 50, stagger: 0.1 });

时间轴 / 复杂序列动画,跟框架无关。商业项目 / 复杂动画神器。

4. Motion One(轻量,2KB) ​

ts
import { animate } from 'motion';
animate('.box', { x: 100 }, { duration: 0.3 });

底层 Web Animations API,性能极好。

5. Lottie(导入设计师做的动画) ​

tsx
import Lottie from 'lottie-react';
import animationData from './animation.json';

<Lottie animationData={animationData} loop />

设计师在 After Effects 做动画 → 用 Bodymovin 导出 JSON → Web 播放,完全保真。

6. 选型 ​

简单 hover / 过渡          → CSS
React 项目复杂交互        → Framer Motion
跨框架 / 复杂时间轴        → GSAP
要轻 + 高性能              → Motion One
设计师做的动画             → Lottie

八、可视化库选型 ​

基础图表(柱状 / 折线 / 饼)
  Chart.js             易用,够用
  Recharts (React)     声明式,简单
  ECharts              功能最全,中文文档好,适合复杂仪表盘
  Apache Superset / Plotly  企业级 / 科学

高级数据可视化
  D3.js                底层,自己组合
  Visx (React)         D3 + React
  Observable Plot       D3 团队新作,声明式
  
地图
  Mapbox GL JS         矢量地图 + WebGL
  Leaflet              轻量,栅格
  deck.gl              海量点 / 3D 地理可视化

3D
  Three.js             通用 3D 库
  Babylon.js           游戏引擎风格
  R3F (React)          Three.js 声明式 React 封装

游戏
  PixiJS               2D
  Phaser               2D 游戏引擎
  Babylon.js           3D 游戏
  Unity WebGL          完整游戏引擎导出

九、性能优化通用原则 ​

  1. 减少 draw call:合并、batch、instancing
  2. 节流绘制:requestAnimationFrame 内做事,别 setInterval
  3. 离屏缓存:复杂图形画一次,后续 drawImage
  4. Web Worker:计算扔到 Worker(OffscreenCanvas)
  5. GPU 对齐数据:Float32Array 传 buffer,别每帧创新数组
  6. 降分辨率:大屏 4K 降到 1.5x DPR,无感
  7. 限制 FPS:不需要 60fps 的可以 30fps
  8. 看 GPU profile:DevTools → Rendering → "Frame rendering stats"

十、常见 Trap ​

Trap 1:Canvas 模糊 ​

js
// 不处理 DPR → Retina 模糊
const dpr = devicePixelRatio;
canvas.width = w * dpr;
canvas.height = h * dpr;
canvas.style.cssText = `width:${w}px;height:${h}px`;
ctx.scale(dpr, dpr);

Trap 2:Three.js 滚动卡 ​

每帧都 render,即使没动也消耗 GPU。改成事件驱动:

ts
// 只在场景变化时 render
controls.addEventListener('change', () => renderer.render(scene, camera));
renderer.render(scene, camera);   // 初始

Trap 3:模型太大首屏卡 ​

3D 模型 50MB → 加载慢 + GPU 上传慢。

  • 用 Draco / Meshopt 压缩
  • LOD(远处低模)
  • 懒加载

Trap 4:Three.js 内存泄漏 ​

切换场景不 dispose:

ts
mesh.geometry.dispose();
mesh.material.dispose();
texture.dispose();
scene.remove(mesh);

不写这些,GPU 内存只增不减。

Trap 5:WebGL Context lost ​

GPU 资源紧张时浏览器会 lose 上下文:

js
canvas.addEventListener('webglcontextlost', (e) => {
  e.preventDefault();
});
canvas.addEventListener('webglcontextrestored', () => {
  // 重新初始化
});

十一、心智模型 ​

图形 API 层级(从简到难):
  SVG       DOM 一份子,适合静态 / 少量 / 可访问
  Canvas 2D 像素,几千~几万元素流畅,2D 游戏
  WebGL     GPU 着色器,3D / 大规模数据
  WebGPU    新一代,2024+ 推荐

实战不裸写,用库:
  Canvas    Konva / PixiJS / ECharts
  WebGL     Three.js(R3F for React)
  动画      Framer Motion / GSAP / Motion One

性能金句:
  "能用 SVG 别用 Canvas,能用 Canvas 别用 WebGL"
  "能用 CSS 动画就别用 JS,能用 transform 别动 layout"

十二、推荐学习路径 ​

按需选,不一定都学:

  1. 简单图表 → Chart.js / Recharts(2 小时)
  2. 自定义画板 / 编辑器 → Konva 或 Fabric(1 天)
  3. 3D 入门 → Three.js Journey 课程(2 周,最受推荐)
  4. 数据可视化 → D3 + Observable(深入)
  5. UI 动效 → Framer Motion(几小时)

十三、参考资源 ​

下一篇 40 讲无障碍 a11y。