JavaScriptで canvas を使うには、HTML内に <canvas> タグを設置し、JavaScriptで描画コンテキストを取得して図形や画像を描きます。以下に、基本的な使い方とポイントをまとめます👇
🖼️ JavaScriptの canvas の使い方(概要)
目次
🧱 1. HTMLに <canvas> を追加
<canvas id="myCanvas" width="400" height="300" style="border:1px solid #000;"></canvas>
📜 2. JavaScriptで描画する
<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d"); // 2D描画コンテキストを取得
// 四角を描画
ctx.fillStyle = "blue";
ctx.fillRect(50, 50, 100, 100);
</script>
🛠️ 主な描画メソッド(2D)
| メソッド | 説明 |
|---|---|
fillRect(x, y, w, h) | 塗りつぶした四角 |
strokeRect(x, y, w, h) | 枠線だけの四角 |
clearRect(x, y, w, h) | その範囲を消去 |
beginPath() / closePath() | パスの開始・終了 |
moveTo(x, y) / lineTo(x, y) | 線を引く |
arc(x, y, r, start, end) | 円・弧を描く |
fillText(text, x, y) | テキスト描画 |
drawImage(img, x, y) | 画像表示 |
🌀 アニメーションもできる!
JavaScriptでは requestAnimationFrame() を使って、スムーズなアニメーションができます。
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(x, 50, 50, 50);
x += 2;
requestAnimationFrame(draw);
}
let x = 0;
draw();
🎮 インタラクティブなイベント対応
canvas.addEventListener("click", function(event) {
const x = event.offsetX;
const y = event.offsetY;
ctx.fillStyle = "green";
ctx.beginPath();
ctx.arc(x, y, 10, 0, Math.PI * 2);
ctx.fill();
});
📦 高度な用途には…
- ゲーム開発(アクション、パズルなど)
- ドローイングアプリ
- データビジュアライゼーション
- インタラクティブなWebアート
✅ まとめ
| 特徴 | 内容 |
|---|---|
| ⭕ 柔軟な描画 | 図形・画像・テキストなど自由に描ける |
| 🎮 ユーザー操作対応 | クリック、マウス移動など |
| 🌀 アニメーション可能 | 滑らかな動きが作れる |
| 🌐 HTML/JS内で使える | ライブラリ不要で始められる |
「簡単な例を作ってみたい」「ゲームっぽい動きが知りたい」などあれば、すぐコード書きます!やりたいことあれば教えてください👍