CanvasRenderingContext2D.scale()
Canvas 2D APIのCanvasRenderingContext2D
.scale()
メソッドは、キャンバス上の長さを縦方向及び横方向に拡縮する変形を適用させます。
By default, one unit on the canvas is exactly one pixel. A scaling transformation modifies this behavior. For instance, a scaling factor of 0.5 results in a unit size of 0.5 pixels; shapes are thus drawn at half the normal size. Similarly, a scaling factor of 2.0 increases the unit size so that one unit becomes two pixels; shapes are thus drawn at twice the normal size.
構文
void ctx.scale(x, y);
引数
x
- 水平方向の拡縮係数。負の値を指定すると、縦軸を跨いでピクセルを反転させます。
1
を指定すると、水平方向には拡縮されません。 y
- 垂直方向の拡縮係数。負の値を指定すると、横軸を跨いでピクセルを反転させます。
1
を指定すると、垂直方向には拡縮されません。
例
図形を拡縮する
この例は、拡縮された長方形を描きます。比較のため、元の長方形も描かれます。
HTML
<canvas id="canvas"></canvas>
JavaScript
The rectangle has a specified width of 8 and a height of 20. The transformation matrix scales it by 9x horizontally and by 3x vertically. 結果的に、幅は72、高さは60になります。
キャンバス上の位置が変わることに注意してください。角の位置の指定値が(10, 10)のため、実際の角の位置は(90, 30)になります。
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 拡縮された長方形
ctx.scale(9, 3);
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 8, 20);
// 変形行列を単位行列に戻す
ctx.setTransform(1, 0, 0, 1, 0, 0);
// 原型の長方形
ctx.fillStyle = 'gray';
ctx.fillRect(10, 10, 8, 20);
結果
拡縮された長方形は赤、元の長方形は灰色です。
垂直・水平方向の反転
You can use scale(-1, 1)
to flip the context horizontally and scale(1, -1)
to flip it vertically. In this example, the words "Hello world!" are flipped horizontally.
Note that the call to fillText()
specifies a negative x coordinate. This is to adjust for the negative scaling factor: -280 * -1
becomes 280
, and text is drawn leftwards from that point.
HTML
<canvas id="canvas"></canvas>
JavaScript
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 Living Standard CanvasRenderingContext2D.scale の定義 |
現行の標準 |
ブラウザの互換性
BCD tables only load in the browser
参考
- このメソッドを定義するインターフェイス:
CanvasRenderingContext2D