
【JavaScript入門】HTML5のCanvas
HTML5 の <canvas> 要素はブラウザ上に “お絵描きボード” をつくり、JavaScript で 図形・文字・画像・アニメーション を自在に描けます。ここでは 2D コンテキスト を使った基礎操作をまとめ、最後に「クリックで花火を描く」デモで手を動かしましょう(3D = WebGL は扱いません)。

1.Canvas の基本仕様と API
| 項目 | 内容 | よく使う値 |
|---|---|---|
| 描画解像度 | width / height 属性で決定 | <canvas width="400" height="300"> |
| 表示サイズ | CSS の width height | style="width:800px;" など |
| 取得 | const cv = document.querySelector('#cv') | ― |
| 2D コンテキスト | const ctx = cv.getContext('2d') | 線や塗りの命令を実行するオブジェクト |
| 座標系 | 原点は 左上 (0,0)、右へ +X、下へ +Y | ctx.fillRect(0,0,50,50) |
代表的メソッド
| メソッド | 概要 |
|---|---|
fillRect(x,y,w,h) | 矩形を塗りつぶし |
strokeRect(x,y,w,h) | 矩形を枠線だけ描画 |
beginPath() / lineTo() / stroke() | パス描画(折れ線・曲線) |
fillText(txt,x,y) | 文字描画 |
drawImage(img,x,y,w,h) | 画像貼り付け |
clearRect(x,y,w,h) | 指定領域を透明に戻す |
2.ファイル構成とポイント
canvas-firework.html… メインページ(下記コード)checker.png… 市松模様 PNG(透明背景を視覚化用に任意用意)
PNGファイルのダウンロードは、ここ「checker.png」からできます。
Canvas のピクセル数 400×300、CSS で等倍表示。クリックした座標から色違いの円を複数描き “ぱっ” と花火が開く簡易デモです。
ファイル名: canvas-firework.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>🎇 Canvas 花火デモ</title>
<style>
body{font-family:"Segoe UI",sans-serif;background:#f7fbff;text-align:center;margin-top:1.5rem}
canvas{background:url(checker.png);border:1px solid #666;border-radius:6px;cursor:pointer}
#msg{margin-top:.6rem;color:#444}
</style>
</head>
<body>
<h1>🎇 Canvas 花火デモ</h1>
<!-- キャンバス -->
<canvas id="cv" width="400" height="300"></canvas>
<div id="msg">キャンバスをクリックしてみてください</div>
<script>
window.addEventListener('DOMContentLoaded',()=>{
const cv = document.getElementById('cv');
const ctx = cv.getContext('2d');
console.log(`${cv}`); // [object HTMLCanvasElement]
console.log(`${ctx}`); // [object CanvasRenderingContext2D]
console.log(cv.width, cv.height); // 400 300
// クリックで花火
cv.addEventListener('click',e=>{
const rect = cv.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
drawFirework(x,y);
});
// 花火を描く(ランダム色+円を5枚)
function drawFirework(cx,cy){
for(let r=10;r<=50;r+=10){
ctx.beginPath();
ctx.arc(cx,cy,r,0,Math.PI*2);
ctx.strokeStyle = randomColor();
ctx.lineWidth = 2;
ctx.stroke();
}
}
const randomColor = ()=>`hsl(${Math.random()*360},80%,60%)`;
});
</script>
</body>
</html>ブラウザの出力例

クリックするたびに原点(左上 0,0)基準の座標を算出し、その位置を中心に円が拡がります。市松模様が透過背景を示し、Canvas 自体は透明から描き始められることが確認できます。
3.コード解説
- コンテキスト取得
const ctx = cv.getContext('2d');‑ これがペンとパレットに相当。 - クリック座標
getBoundingClientRect()でキャンバスの表示位置を得て、clientX/Yから差分を計算。 arc()で円描画
角度 0 →Math.PI*2で一周。ループで半径を変え同心円。strokeStyleに HSL 乱数
カラフルな線色が毎回変化。- 背景画像 + 枠線
Canvas は初期全透明。市松 PNG を敷きピクセル境界を分かりやすく。
まとめ
Canvas 2D は
<canvas>タグで描画領域を用意getContext('2d')でツールを取得- 図形 API を呼ぶだけで即座に描画
という3ステップで利用できます。今回の花火デモを土台に、requestAnimationFrame を加えれば本格的なアニメーションやゲーム画面を構築可能です。次の章では フレームごとに描き直す動くキャンバス に挑戦してみましょう。
