150*100 ピクセルの矩形を描画します:
JavaScript:
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.rect(20,20,150,100);
ctx.stroke();
Try it Yourself ❯
表中の数字は、メソッドを完全にサポートした最初のブラウザ・バージョンを指定しています。
メソッド | |||||
---|---|---|---|---|---|
rect() | Yes | 9.0 | Yes | Yes | Yes |
rect() メソッドは、矩形を作成します。
チップ: 実際にキャンバス上に矩形を描画するには、stroke() または fill() メソッドを使用します。
JavaScript 構文: | context.rect(x,y,width,height); |
---|
パラメータ | 説明 | Play it |
---|---|---|
x | 矩形の左上隅の x 座標 | Play it ❯ |
y | 矩形の左上隅の y 座標 | Play it ❯ |
width | 矩形の幅(ピクセル単位) | Play it ❯ |
height | 矩形の高さ(ピクセル単位) | Play it ❯ |
Create three rectangles with the rect() メソッドにより 3 つの矩形を作成します:
JavaScript:
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
// Red rectangle
ctx.beginPath();
ctx.lineWidth="6";
ctx.strokeStyle="red";
ctx.rect(5,5,290,140);
ctx.stroke();
// Green rectangle
ctx.beginPath();
ctx.lineWidth="4";
ctx.strokeStyle="green";
ctx.rect(30,30,50,50);
ctx.stroke();
// Blue rectangle
ctx.beginPath();
ctx.lineWidth="10";
ctx.strokeStyle="blue";
ctx.rect(50,50,150,80);
ctx.stroke();
Try it Yourself ❯