Canvas API 基本2

Canvas APIの基本2

上の画像のコードは、 円を描くarc()、 テキストを描画するfillText()、 画像を描くdrawImage()などを使っています。 コードは下の様になります。


<canvas class="Canv">
    
</canvas>

<script>
  const canvas = document.querySelector('.Canv');
  const width = canvas.width = window.innerWidth;
  const height = canvas.height = window.innerHeight; 

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

  ctx.fillStyle = 'rgb(255,255,255)';
  ctx.fillRect(0, 0, width, height);
 
  function degToRad(degrees) {
  return degrees * Math.PI / 180;
  };

  ctx.fillStyle = 'green';
  ctx.beginPath();
  ctx.arc(200, 100, 70, degToRad(-30), degToRad(35), true);
  ctx.lineTo(200, 100);
  ctx.fill(); 

  ctx.fillStyle = 'blue';
  ctx.font = '32px arial';
  ctx.fillText('パックマン,テキスト,イメージ', 50, 150);

  const image = new Image();
      image.src = 'img2.png';
      image.onload = function() {
        ctx.drawImage(image, 0, 0, 300, 155, 100, 200, 300, 155);
      }
 
</script>

上記コードを簡単に説明します。 ctx.arc(200, 100, 70, degToRad(-30), degToRad(35), true) の引数は、 1番と2番は円弧の中心のxとyの位置、 3番目は半径、 4番目は開始角度、5番目は終了角度、 6番目は反時計回りがtrue、 時計回りがfalseです。 ctx.fillText('パックマン,テキスト,イメージ', 50, 150) の引数は、 1番目は描画するテキスト文字列、 2番目と3番目は 描画を開始するXとYの位置、 ctx.drawImage(image, 0, 0, 300, 155, 100, 200, 300, 155) の引数は、 1番目イメージリファレンス、 2番目、3番目はロードイメージの左上隅からのXとYの位置、 4番目はオリジナルイメージの切り取り幅、5番目はオリジナルイメージの切り取り高さ、 6番目、7番目はキャンパスの左上隅からのXとYの開始位置、 8番目、9番目はキャンパスの表示幅と表示高さです。

スタイルのコードは下記になります。 overflowは、 ブロック整形コンテキストに収まらない場合の設定です。 scrollは、 スクロールバーを表示します。 hiddenは、 収まらない箇所を隠します。 visibleは、 収まらない箇所も表示します。

body { margin: 0; overflow: scroll; }