You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用DOMMatrix实现Canvas变换?旧API替代及文档疑问

用DOMMatrix实现Canvas 2D变换的方法

MDN提到的旧版rotate()、scale()等变换方法并未完全废弃,只是推荐使用更灵活的DOMMatrix来统一处理Canvas变换——它能更方便地组合、复用和管理复杂变换逻辑。以下是具体实现方式:

核心用法:通过DOMMatrix操作上下文变换

CanvasRenderingContext2D提供了transform属性和setTransform()方法来应用DOMMatrix:

  • setTransform(matrix):完全替换当前的变换矩阵(等价于重置后应用新变换)
  • ctx.transform = matrix:在当前变换基础上叠加新矩阵(等价于旧方法的叠加行为)

1. 基础变换示例(旋转、缩放、平移)

创建单个变换矩阵并应用:

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

// 创建旋转45度的矩阵
const rotateMatrix = new DOMMatrix().rotate(45);
// 应用变换(完全替换当前矩阵)
ctx.setTransform(rotateMatrix);

// 绘制应用了旋转的矩形
ctx.fillStyle = 'red';
ctx.fillRect(50, 50, 100, 100);

2. 组合多个变换

DOMMatrix的方法支持链式调用,可轻松组合平移、旋转、缩放等操作:

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

// 组合变换:先平移到画布中心,再旋转30度,最后放大1.5倍
const combinedMatrix = new DOMMatrix()
  .translate(200, 200)  // 平移原点到画布中心(200,200)
  .rotate(30)           // 绕原点旋转30度
  .scale(1.5);          // 沿x/y轴放大1.5倍

// 应用组合变换
ctx.setTransform(combinedMatrix);

// 绘制中心在画布原点的正方形(实际显示在画布中心)
ctx.fillStyle = 'blue';
ctx.fillRect(-50, -50, 100, 100);

3. 叠加变换

如果需要在已有变换基础上叠加新变换,直接修改ctx.transform属性即可:

// 先应用初始平移
ctx.setTransform(new DOMMatrix().translate(100, 100));

// 叠加旋转变换
ctx.transform = ctx.transform.multiply(new DOMMatrix().rotate(45));

// 绘制的图形会同时应用平移+旋转
ctx.fillStyle = 'green';
ctx.fillRect(0, 0, 80, 80);

与旧方法的对应关系

旧版变换方法本质是对当前矩阵的叠加操作,用DOMMatrix可以完全替代:

  • ctx.rotate(angle) → ctx.transform = ctx.transform.multiply(new DOMMatrix().rotate(angle))
  • ctx.scale(x, y) → ctx.transform = ctx.transform.multiply(new DOMMatrix().scale(x, y))
  • ctx.translate(x, y) → ctx.transform = ctx.transform.multiply(new DOMMatrix().translate(x, y))

为什么用DOMMatrix?

相比旧方法,DOMMatrix的优势在于:

  • 可以提前创建、保存和复用变换矩阵,适合复杂动画或多元素共享变换的场景
  • 支持更精细的矩阵运算(如矩阵相乘、逆矩阵)
  • 统一了DOM和Canvas的变换逻辑(SVG、CSS变换也支持DOMMatrix)

内容的提问来源于stack exchange,提问作者Jez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 16:10:32