JavaScriptのcanvas要素で矩形を描画するfillRect()メソッドについて、基本的な使い方から実践的なコード例まで詳しく解説します。
fillRect()メソッドとは
fillRect()は、HTMLのcanvas要素に塗りつぶされた矩形を描画するためのメソッドです。2D描画コンテキストのメソッドとして提供されています。
基本的な書き方
context.fillRect(x, y, width, height);- x: 矩形の左上のX座標
- y: 矩形の左上のY座標
- width: 矩形の幅
- height: 矩形の高さ
シンプルな実装例
// canvasの取得
const canvas = document.getElementById('myCanvas');
const context = canvas.getContext('2d');
// 青色の矩形を描画
context.fillStyle = 'blue';
context.fillRect(10, 10, 100, 50);実践的なコード例
<!DOCTYPE html>
<html>
<head>
<title>矩形描画サンプル</title>
</head>
<body>
<canvas id="myCanvas" width="300" height="200"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const context = canvas.getContext('2d');
// 背景色の設定
context.fillStyle = 'lightgray';
context.fillRect(0, 0, canvas.width, canvas.height);
// 赤い矩形
context.fillStyle = 'red';
context.fillRect(50, 50, 100, 80);
// 青い矩形
context.fillStyle = 'blue';
context.fillRect(150, 100, 80, 60);
</script>
</body>
</html>応用テクニック
透明度の設定
context.globalAlpha = 0.5; // 0.0から1.0の値
context.fillRect(10, 10, 100, 50);グラデーション効果
const gradient = context.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, 'red');
gradient.addColorStop(1, 'blue');
context.fillStyle = gradient;
context.fillRect(10, 10, 200, 100);よくあるエラーと解決策
1. canvas要素が見つからない
// 解決策:IDが正しいか確認
const canvas = document.getElementById('myCanvas');
if (!canvas) {
console.error('Canvas要素が見つかりません');
return;
}2. 2Dコンテキストが取得できない
// 解決策:getContextの引数を確認
const context = canvas.getContext('2d');
if (!context) {
console.error('2Dコンテキストが取得できません');
return;
}まとめ
fillRect()メソッドは、JavaScriptでcanvasに矩形を描画する基本的な機能を提供します。座標と大きさを指定するだけで簡単に矩形を描画できます。色やグラデーション、透明度などを組み合わせることで、より魅力的な表現が可能です。
エラーが発生した場合は、canvas要素のIDや2Dコンテキストの取得方法を確認することで、多くの問題を解決できます。