TypeError: Cannot read properties of undefined (reading 'moveTo')

このエラーメッセージは、JavaScriptでcanvasのパス描画時によく発生するエラーです。本記事では、moveToメソッドの基本から実装例とエラー解決方法まで解説します。

moveToメソッドとは

moveToメソッドは、Canvas 2D APIで提供されているメソッドで、新しいサブパスの開始点を座標で指定します。ペンやブラシを紙に置くイメージです。

基本的な書式は以下の通りです:

context.moveTo(x, y)
  • x: 新しい開始点のX座標
  • y: 新しい開始点のY座標

よくあるエラーの原因と解決法

1. コンテキストが取得できていない

最も多い原因は、canvas要素の2Dコンテキストが正しく取得できていない場合です。

エラーが出るコード:

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
ctx.moveTo(100, 100); // エラー発生

解決策:

const canvas = document.getElementById('myCanvas');
if (canvas) {
  const ctx = canvas.getContext('2d');
  if (ctx) {
    ctx.moveTo(100, 100); // 正常に動作
  }
}

2. DOM読み込み前にコードが実行される

canvas要素が読み込まれる前にJavaScriptが実行されることでエラーが発生する場合があります。

解決策:

document.addEventListener('DOMContentLoaded', () => {
  const canvas = document.getElementById('myCanvas');
  const ctx = canvas.getContext('2d');
  ctx.moveTo(100, 100);
});

基本的な使用例

直線を描画する

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

ctx.beginPath();
ctx.moveTo(50, 50);    // 開始点を設定
ctx.lineTo(200, 200);  // 終点を設定
ctx.stroke();          // 実際に描画

複数の線を繋げる

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

ctx.beginPath();
ctx.moveTo(50, 50);     // 開始点
ctx.lineTo(200, 50);    // 1本目の線
ctx.lineTo(200, 200);   // 2本目の線
ctx.lineTo(50, 200);    // 3本目の線
ctx.closePath();        // パスを閉じる
ctx.stroke();           // 描画

エラーを防ぐためのベストプラクティス

1. 必ず存在チェックを行う

if (!canvas || !ctx) {
  console.error('Canvas or context not available');
  return;
}

2. パスの開始と終了を明示的に行う

ctx.beginPath();
ctx.moveTo(x, y);
// 描画処理
ctx.closePath();

3. エラーハンドリングを実装する

try {
  const canvas = document.getElementById('myCanvas');
  const ctx = canvas.getContext('2d');
  ctx.moveTo(100, 100);
} catch (error) {
  console.error('Error drawing on canvas:', error);
}

まとめ

moveToメソッドは、Canvas上でパス描画の開始点を指定する重要なメソッドです。エラーを防ぐためには:

  • canvas要素とコンテキストの存在確認
  • DOMの読み込み完了後に処理を実行
  • 適切なエラーハンドリング

これらの点に注意して実装することで、安定したCanvas描画処理を実現できます。