CanvasRenderingContext2D.setTransform()

CanvasRenderingContext2D.setTransform() 是 Canvas 2D API 使用单位矩阵重新设置(覆盖)当前的变换并调用变换的方法,此变换由方法的变量进行描述。

参见 transform() 方法,这个方法不会覆盖当前的变换矩阵,会多次叠加变换。

语法

void ctx.setTransform(a, b, c, d, e, f);

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

参数

a (m11)
水平缩放。
b (m12)
垂直倾斜。
c (m21)
水平倾斜。
d (m22)
垂直缩放。
e (dx)
水平移动。
f (dy)
垂直移动。

较新的类型由单个参数矩阵组成,该参数表示要设置的2D转换矩阵(从技术上讲,是DOMMatrixInit对象;任何对象只要包含上述作为属性的组件,就可以执行操作)。

示例

使用 setTransform 方法

这是一段使用 setTransform 方法的简单的代码片段。

HTML

<canvas id="canvas"></canvas>

JavaScript

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

ctx.setTransform(1,1,0,1,0,0);
ctx.fillRect(0,0,100,100);

修改下面的代码并在线查看 canvas 的变化:

Playable code
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>
<div class="playable-buttons">
  <input id="edit" type="button" value="Edit" />
  <input id="reset" type="button" value="Reset" />
</div>
<textarea id="code" class="playable-code">
ctx.setTransform(1,1,0,1,0,0);
ctx.fillRect(0,0,100,100);</textarea>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var textarea = document.getElementById("code");
var reset = document.getElementById("reset");
var edit = document.getElementById("edit");
var code = textarea.value;

function drawCanvas() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  eval(textarea.value);
}

reset.addEventListener("click", function() {
  textarea.value = code;
  drawCanvas();
});

edit.addEventListener("click", function() {
  textarea.focus();
})

textarea.addEventListener("input", drawCanvas);
window.addEventListener("load", drawCanvas);

规范描述

Specification Status Comment
HTML Living Standard
CanvasRenderingContext2D.setTransform
Living Standard

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
setTransformChrome Full support YesEdge Full support 12Firefox Full support 3IE Full support YesOpera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yes
Accept matrix object as parameterChrome 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

参见