CanvasRenderingContext2D:translate() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

Canvas 2D API 的 CanvasRenderingContext2D.translate() 方法會將一個平移變換新增到當前矩陣。

語法

js
translate(x, y)

translate() 方法透過在網格上水平移動畫布及其原點 x 個單位,並在垂直方向上移動 y 個單位,來將平移變換新增到當前矩陣。

A canvas's origin moved on the x and y axes based on the values of the translate method.

引數

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

瀏覽器相容性

另見