Canvasと2Dコンテキストのセットアップ
canvas要素を作成し、2D描画コンテキストを取得します
「Canvasと2Dコンテキストのセットアップ」はCoddyKit上の無料HTML Academyレッスンです。 これはレッスン1/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはHTML Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 HTML Academyコースには全4レッスンが含まれています。
canvas要素
<canvas>要素は、ブラウザー上で描画できるビットマップ領域です。
<canvas id="myCanvas" width="800" height="400">
<!-- Fallback for browsers without canvas support -->
<p>Your browser does not support HTML5 Canvas.</p>
</canvas>widthとheight属性
canvasのサイズは、CSSではなく必ずHTML属性で設定します。
<!-- CORRECT: set intrinsic size via attributes -->
<canvas width="800" height="400"></canvas>
<!-- WRONG: CSS changes display size but not canvas resolution -->
<canvas style="width: 800px; height: 400px;"></canvas>
<!-- This stretches a default 300x150 canvas to 800x400
Result: blurry graphics -->2Dコンテキストを取得する
描画するには2Dレンダリングコンテキストを取得します。
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// ctx is a CanvasRenderingContext2D object
// All drawing operations are methods on ctx
// Check browser support:
if (!canvas.getContext) {
console.error('Canvas not supported');
}座標系
canvasの座標系は左上から始まります。
// (0, 0) = top-left corner
// (width, 0) = top-right
// (0, height) = bottom-left
// (width, height) = bottom-right
// For a 800x400 canvas:
// x increases left → right (0 to 800)
// y increases top → bottom (0 to 400)
//
// Example: draw at center:
ctx.fillRect(400, 200, 10, 10); // centered dotcanvasの状態
canvasには保存および復元できる描画状態があります。
ctx.save(); // push current state onto a stack
// Change state:
ctx.fillStyle = 'red';
ctx.globalAlpha = 0.5;
// Draw with modified state...
ctx.fillRect(100, 100, 200, 200);
ctx.restore(); // pop state: back to pre-save settingscanvasを消去する
再描画(アニメーション)の前に、canvas全体を消去します。
// Clear entire canvas:
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Or with a background color:
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width, canvas.height);fillStyleとstrokeStyle
塗りつぶしと線の描画に使う色を設定します。
ctx.fillStyle = 'blue'; // CSS color name
ctx.fillStyle = '#ff6600'; // hex color
ctx.fillStyle = 'rgb(255, 100, 0)'; // rgb
ctx.fillStyle = 'rgba(255, 100, 0, 0.5)'; // rgba with alpha
ctx.fillStyle = gradient; // gradient object
ctx.fillStyle = pattern; // pattern object
ctx.strokeStyle = '#333333'; // border colorlineWidthとその他のスタイルプロパティ
線と描画スタイルに関するプロパティです。
ctx.lineWidth = 4; // stroke width in pixels
ctx.lineCap = 'round'; // butt | round | square
ctx.lineJoin = 'round'; // miter | round | bevel
ctx.setLineDash([5, 3]); // dashed line: 5px dash, 3px gap
ctx.globalAlpha = 0.8; // transparency for all drawing
ctx.globalCompositeOperation = 'multiply'; // blend modesレスポンシブなHiDPI canvas
RetinaやHiDPIディスプレイでcanvasがぼやける問題を解消します。
function setupHiDPI(canvas, width, height) {
const dpr = window.devicePixelRatio || 1;
canvas.width = width * dpr;
canvas.height = height * dpr;
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';
const ctx = canvas.getContext('2d');
ctx.scale(dpr, dpr); // scale all drawing
return ctx;
}canvasとSVGの比較
canvasとSVGを使い分ける基準:
- Canvas — ビットマップで、ピクセル単位の処理に適しており、ゲーム、大規模なデータ可視化、画像処理に向いています
- SVG — ベクター形式で拡大縮小に強く、ロゴ、アイコン、インタラクティブな要素を持つグラフ、アクセシビリティに向いています
canvasのアクセシビリティ
canvasにはアクセシビリティ機能が組み込まれていないため、手動で追加します。
<canvas
id="chart"
width="800"
height="400"
aria-label="Bar chart showing Q1-Q4 revenue growth"
role="img"
>
<!-- Fallback for non-canvas browsers and screen readers -->
<table><!-- accessible data table --></table>
</canvas>確認問題
canvasの描画コンテキストを取得する正しい方法は何ですか?
まとめ:canvasの設定
canvas設定の要点:
- widthとheightはCSSではなくHTML属性で設定します
canvas.getContext('2d')— 描画コンテキストを取得します- 原点は左上の(0,0)で、xは右方向、yは下方向に増加します
ctx.save()/ctx.restore()— スタックベースで状態を管理します- devicePixelRatioに合わせて拡大し、Retinaでも鮮明に描画します
よくある質問
「Canvasと2Dコンテキストのセットアップ」レッスンは無料ですか?
はい。「Canvasと2Dコンテキストのセットアップ」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、HTML Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 HTML Academyコースには全4レッスンが含まれています。
「Canvasと2Dコンテキストのセットアップ」で何を学びますか?
canvas要素を作成し、2D描画コンテキストを取得します ブラウザで直接実行するハンズオンコードでHTML Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
HTML Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのHTML Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン1/4です。
「Canvasと2Dコンテキストのセットアップ」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このHTML Academyレッスンでコードを書いて実行できますか?
はい。すべてのHTML Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- Canvasと2Dコンテキストのセットアップ
- 長方形とパスを描画する
- Canvas上のテキストと画像
- requestAnimationFrameによるアニメーション