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

浏览器兼容性

另见