Canvas 2D APIのCanvasRenderingContext2D
.rect()
メソッドは、2Dウィンドウのサイズ(width, height)や開始位置(x, y)を定義できるメソッドです。
ウィンドウのサイズと開始位置をもとに直線で引かれたウィンドウが2Dウィンドウになり、fill
メソッドでウィンドウ内の塗りつぶしをしたり、stroke
メソッドでウィンドウの外周を直線で囲み、可視化することなどできます。
構文
void ctx.rect(x, y, width, height);
パラメーター
x
-
2Dウィンドウの開始位置(x軸)
y
-
2Dウィンドウの開始位置(y軸)
width
-
2Dウィンドウの幅
height
-
2Dウィンドウの高さ
例
rect メソッドの使用方法
この例は、 rect
メソッドを使用してウィンドウの作成をするシンプルなコードです。
内容は、canvas内に作成したウィンドウに対して、fill()
を実行し、ウィンドウ内を黒塗りにしているだけになります。
上に記載してあるウィンドウを黒塗りする fill()
以外にも、
などが存在しているので、参考にしてみてください。
HTML
<canvas id="canvas"></canvas>
JavaScript
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.rect(10, 10, 100, 100);
ctx.fill();
下のコードを変更してみよう:
仕様書
仕様書 | ステータス | 備考 |
---|---|---|
HTML Living Standard CanvasRenderingContext2D.rect の定義 |
現行の標準 |
ブラウザー実装状況
BCD tables only load in the browser
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.