CanvasRenderingContext2D:translate() 方法
Canvas 2D API 的 CanvasRenderingContext2D.translate() 方法會將一個平移變換新增到當前矩陣。
語法
js
translate(x, y)
translate() 方法透過在網格上水平移動畫布及其原點 x 個單位,並在垂直方向上移動 y 個單位,來將平移變換新增到當前矩陣。

引數
返回值
無(undefined)。
示例
移動圖形
本示例繪製了一個正方形,該正方形透過 translate() 方法從其預設位置移動。然後繪製一個相同大小但未移動的正方形以供比較。
HTML
html
<canvas id="canvas"></canvas>
JavaScript
translate() 方法在水平方向上將上下文平移 110 個單位,在垂直方向上平移 30 個單位。第一個正方形從其預設位置偏移了這些量。
js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
// Moved square
ctx.translate(110, 30);
ctx.fillStyle = "red";
ctx.fillRect(0, 0, 80, 80);
// Reset current transformation matrix to the identity matrix
ctx.setTransform(1, 0, 0, 1, 0, 0);
// Unmoved square
ctx.fillStyle = "gray";
ctx.fillRect(0, 0, 80, 80);
結果
移動後的正方形為紅色,未移動的正方形為灰色。
規範
| 規範 |
|---|
| HTML # dom-context-2d-translate-dev |
瀏覽器相容性
載入中…
另見
- 定義此方法的介面:
CanvasRenderingContext2D