CanvasRenderingContext2D: scale() 方法

Baseline 已廣泛支援

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

Canvas 2D API 的 CanvasRenderingContext2D.scale() 方法會在畫布座標系中新增一個水平和/或垂直的縮放變換。

預設情況下,畫布上的一個單位等於一個畫素。縮放變換會改變這種行為。例如,縮放因子為 0.5 會導致單位大小為 0.5 畫素;因此,形狀會以正常大小的一半繪製。類似地,縮放因子為 2.0 會增加單位大小,使一個單位等於兩個畫素;因此,形狀會以正常大小的兩倍繪製。

語法

js
scale(x, y)

引數

x

水平方向的縮放因子。負值會沿著垂直軸翻轉畫素。值為 1 表示不進行水平縮放。

y

垂直方向的縮放因子。負值會沿著水平軸翻轉畫素。值為 1 表示不進行垂直縮放。

返回值

無(undefined)。

示例

縮放形狀

此示例繪製了一個縮放後的矩形。然後會繪製一個未縮放的矩形進行對比。

HTML

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

JavaScript

該矩形指定的寬度為 8,高度為 20。變換矩陣將其水平放大 9 倍,垂直放大 3 倍。因此,其最終尺寸為寬度 72,高度 60。

請注意,它在畫布上的位置也會發生變化。由於其指定的角落是 (10, 10),渲染後的角落變為 (90, 30)。

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

// Scaled rectangle
ctx.scale(9, 3);
ctx.fillStyle = "red";
ctx.fillRect(10, 10, 8, 20);

// Reset current transformation matrix to the identity matrix
ctx.setTransform(1, 0, 0, 1, 0, 0);

// Non-scaled rectangle
ctx.fillStyle = "gray";
ctx.fillRect(10, 10, 8, 20);

結果

縮放後的矩形為紅色,未縮放的矩形為灰色。

水平或垂直翻轉

您可以使用 scale(-1, 1) 來水平翻轉上下文,使用 scale(1, -1) 來垂直翻轉上下文。在此示例中,“Hello world!” 這句話被水平翻轉了。

請注意,呼叫 fillText() 時指定了一個負的 x 座標。這是為了調整負的縮放因子:-280 * -1 變為 280,然後文字會從此點向左繪製。

HTML

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

JavaScript

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

ctx.scale(-1, 1);
ctx.font = "48px serif";
ctx.fillText("Hello world!", -280, 90);
ctx.setTransform(1, 0, 0, 1, 0, 0);

結果

規範

規範
HTML
# dom-context-2d-scale-dev

瀏覽器相容性

另見