--- title: CanvasRenderingContext2D.transform() slug: Web/API/CanvasRenderingContext2D/transform translation_of: Web/API/CanvasRenderingContext2D/transform ---
CanvasRenderingContext2D
.transform()
是 Canvas 2D API 使用矩阵多次叠加当前变换的方法,矩阵由方法的参数进行描述。你可以缩放、旋转、移动和倾斜上下文。
参见 {{domxref("CanvasRenderingContext2D.setTransform()", "setTransform()")}} 方法,这个方法使用单位矩阵重新设置当前的变换并且会调用 transform()。
void ctx.transform(a, b, c, d, e, f);
变换矩阵的描述:
a (m11)
b (m12)
c (m21)
d (m22)
e (dx)
f (dy)
transform
方法这是一段使用 transform
方法的简单的代码片段。
<canvas id="canvas"></canvas>
var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); ctx.transform(1,1,0,1,0,0); ctx.fillRect(0,0,100,100);
修改下面的代码并在线查看 canvas 的变化:
<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.transform(1,1,0,1,0,0); ctx.fillRect(0,0,100,100); ctx.setTransform(); </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; ctx.setTransform(1, 0, 0, 1, 0, 0); drawCanvas(); }); edit.addEventListener("click", function() { textarea.focus(); }) textarea.addEventListener("input", drawCanvas); window.addEventListener("load", drawCanvas);
{{ EmbedLiveSample('Playable_code', 700, 360) }}
Specification | Status | Comment |
---|---|---|
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-transform", "CanvasRenderingContext2D.transform")}} | {{Spec2('HTML WHATWG')}} |
{{ CompatibilityTable() }}
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} | {{ CompatVersionUnknown() }} |