CanvasRenderingContext2D.getTransform()

CanvasRenderingContext2D.getTransform() 方法获取当前被应用到上下文的转换矩阵

语法

let storedTransform = ctx.getTransform();

参数

无.

返回值

一个 DOMMatrix 对象

转换矩阵被这样描述: [acebdf001]\left[ \begin{array}{ccc} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{array} \right]

注意: 返回的对象不是实时的,所以更新它不会影响当前的转换矩阵,同时更新当前的转换矩阵不会影响已经返回的 DOMMatrix.

示例

在以下例子,我们有两个 <canvas> 元素。我们使用  CanvasRenderingContext2D.setTransform() 设置一个转换到第一个画布,并在上面画一个矩形,然后通过 getTransform() 获取矩阵。

然后我们将获取到的矩阵作为 DOMMatrix 参数传给 setTransform() 设置到第二个画布,并在上面画一个圆。

HTML

<canvas width="240"></canvas>
<canvas width="240"></canvas>

CSS

canvas {
  border: 1px solid black;
}

JavaScript

const canvases = document.querySelectorAll('canvas');
const ctx1 = canvases[0].getContext('2d');
const ctx2 = canvases[1].getContext('2d');

ctx1.setTransform(1, .2, .8, 1, 0, 0);
ctx1.fillRect(25, 25, 50, 50);

let storedTransform = ctx1.getTransform();
console.log(storedTransform);

ctx2.setTransform(storedTransform);
ctx2.beginPath();
ctx2.arc(50, 50, 50, 0, 2 * Math.PI);
ctx2.fill();

结果

规范

Specification Status Comment
HTML Living Standard
CanvasRenderingContext2D.getTransform
Living Standard

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
getTransformChrome Full support 68Edge Full support 79Firefox Full support 70IE No support NoOpera Full support 55Safari Full support 11WebView Android Full support 68Chrome Android Full support 68Firefox Android No support NoOpera Android Full support 48Safari iOS Full support 11Samsung Internet Android Full support 10.0

Legend

Full support  
Full support
No support  
No support

参见