TypeScriptで学ぶ「CanvasRenderingContext2D」の使い方

CanvasRenderingContext2Dとは

CanvasRenderingContext2DはHTML5 の <canvas> 要素で2D描画を行うためのインターフェースです。

<canvas> 要素の getContext('2d') を呼び出すことで取得でき、図形の描画、テキストの描画、画像の操作などが可能になります。

CanvasRenderingContext2Dの使い方

まず、HTML内に<canvas> 要素を以下のように追加します。

canvasの範囲が視覚的にわかるようにborderも付けています。

HTML
<style>
canvas {
  border: 1px solid #000;
}
</style>

<canvas id="canvas" width="300" height="300"></canvas>

次にTypeScriptでgetContext('2d')を使って、CanvasRenderingContext2Dを取得し、描画の準備をします。

TypeScript
const canvas = document.getElementById('canvas') as HTMLCanvasElement
if (!canvas) {
  throw new Error('canvasの要素がありません')
}

const ctx = canvas.getContext('2d')
if (!ctx) {
  throw new Error('2D contextが取得できませんでした')
}

TypeScriptの場合、canvasに「as HTMLCanvasElement」を付けないと型推論でcanvasが「HTMLElement」となって警告が表示されるので、必ず「as HTMLCanvasElement」を付けてください。

これを付けておけば、ctxの型が「CanvasRenderingContext2D | null」と型推論されます。

ちなみにctxはcontextの略で、canvasを使用する際によく使用される略称です。

次に以下のコードを書いてみてください。

家や月などが描画されます。canvasはベクターではなくビットマップなので、描画は粗いです。

TypeScript
// 線の太さ
ctx.lineWidth = 10

// 線の色
ctx.strokeStyle = 'blue'

// 壁
// void ctx.strokeRect(x, y, width, height)
ctx.strokeRect(75, 140, 150, 110)

// 塗りつぶしの色
ctx.fillStyle = 'red'

// ドア
// void ctx.fillRect(x, y, width, height)
ctx.fillRect(130, 185, 40, 60)

// 屋根
ctx.strokeStyle = 'green'
ctx.beginPath()
ctx.moveTo(50, 140)
ctx.lineTo(150, 60)
ctx.lineTo(250, 140)
ctx.closePath()
ctx.stroke()

// 月
ctx.beginPath()
ctx.fillStyle = 'yellow'
// arc(x, y, radius, startAngle, endAngle, counterclockwise)
ctx.arc(250, 50, 30, 0, Math.PI * 2, false)
ctx.fill()

// 角丸四角形
const x = 100, y = 265
const width = 100, height = 30
const radius = 10

ctx.beginPath()
ctx.moveTo(x + radius, y)
ctx.arcTo(x + width, y, x + width, y + height, radius)
ctx.arcTo(x + width, y + height, x, y + height, radius)
ctx.arcTo(x, y + height, x, y, radius)
ctx.arcTo(x, y, x + width, y, radius)
ctx.fillStyle = 'brown'
ctx.fill()
ctx.closePath()

CanvasRenderingContext2Dのサンプル

描画の保存と復元

save()およびrestore()を使用することで、ctxに設定した状態の保存と復元が可能です。

TypeScript
const canvas = document.getElementById('canvas') as HTMLCanvasElement
if (!canvas) {
  throw new Error('canvasの要素がありません')
}

const ctx = canvas.getContext('2d')
if (!ctx) {
  throw new Error('2D contextが取得できませんでした')
}

// 現在の状態を保存する
ctx.fillStyle = 'red'
ctx.save()

// 緑の四角形を描画する
ctx.fillStyle = 'green'
ctx.fillRect(10, 20, 100, 100)

// 保存した状態を復元する
ctx.restore()

// 赤の四角形を描画する
ctx.fillRect(150, 80, 100, 100)

CanvasRenderingContext2D save()およびrestore()のサンプル