Canvas API

Frontend SELF JA
レベル 42 , レッスン 4
使用可能

10.1 Canvasの基礎

Canvas APIは、ウェブアプリで2Dグラフィックやアニメーションを作成するための良いツールを提供してくれるよ。この講義では、Canvas APIの基本操作、要素の作成、グラフィックの描画、アニメーションの作成について見ていこう。

<canvas>要素の作成

HTMLの<canvas>要素は、いろいろなグラフィックオペレーションを実行できる描画領域を作成するために使われるよ:

HTML
    
      <canvas id="myCanvas" width="800" height="600"></canvas>
    
  

描画コンテキストの取得

<canvas>要素で描画操作を行うには、描画コンテキストを取得する必要があるんだ。2Dグラフィックには2dコンテキストを使うよ:

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

10.2 Canvasでの描画

1. 長方形

Canvas APIは、塗りつぶされた長方形とフレーム付きの長方形を描画するためのメソッドを提供しているよ。

塗りつぶし矩形 — fillRect:

HTML
    
      <html>
        <head>
          <title>Document</title>
        </head>
        <body>
          <canvas id="myCanvas" width="800" height="600"></canvas>

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

            ctx.fillStyle = 'blue';
            ctx.fillRect(10, 10, 150, 100);
          </script>
        </body>
      </html>
    
  

フレーム付き長方形 — strokeRect:

HTML
    
      <html>
        <head>
          <title>Document</title>
        </head>
        <body>
          <canvas id="myCanvas" width="800" height="600"></canvas>

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

            ctx.strokeStyle = 'red';
            ctx.strokeRect(200, 10, 150, 100);
          </script>
        </body>
      </html>
    
  

領域のクリア

clearRectメソッドは、特定の領域をクリアするために使われるよ:

HTML
    
      <html>
        <head>
          <title>Document</title>
        </head>
        <body>
          <canvas id="myCanvas" width="800" height="600"></canvas>

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

            ctx.strokeStyle = 'red';
            ctx.strokeRect(200, 10, 150, 100);

            ctx.clearRect(0, 0, 800, 600);
          </script>
        </body>
      </html>
    
  

2. 線

線を描画するには、新しいパスを始めるためにbeginPathメソッドを使うよ。そこからmoveTolineToメソッドで線の座標を決めるんだ:

HTML
    
      <html>
        <head>
          <title>Document</title>
        </head>
        <body>
          <canvas id="myCanvas" width="800" height="600"></canvas>

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

            ctx.beginPath();
            ctx.moveTo(50, 150);
            ctx.lineTo(250, 150);
            ctx.lineTo(150, 300);
            ctx.closePath();
            ctx.stroke();
          </script>
        </body>
      </html>
    
  

3. 円と弧

arcメソッドは、円や弧を描くために使われるよ:

HTML
    
      <html>
        <head>
          <title>Document</title>
        </head>
        <body>
          <canvas id="myCanvas" width="800" height="600"></canvas>

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

            ctx.beginPath();
            ctx.arc(400, 75, 50, 0, Math.PI * 2);
            ctx.fillStyle = 'green';
            ctx.fill();
          </script>
        </body>
      </html>
    
  

4. テキスト

fillTextstrokeTextメソッドは、テキストを描画するために使われるよ:

HTML
    
      <html>
        <head>
          <title>Document</title>
        </head>
        <body>
          <canvas id="myCanvas" width="800" height="600"></canvas>

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

            ctx.font = '30px Arial';
            ctx.fillStyle = 'black';
            ctx.fillText('Hello Canvas', 10, 350);
          </script>
        </body>
      </html>
    
  

5. グラデーション

Canvas APIは線形グラデーションと放射状グラデーションの作成をサポートしているよ。

線形グラデーション:

HTML
    
      <html>
        <head>
          <title>Document</title>
        </head>
        <body>
          <canvas id="myCanvas" width="800" height="600"></canvas>

          <script>
            const canvas = document.getElementById('myCanvas');
            const ctx = canvas.getContext('2d');
            const gradient = ctx.createLinearGradient(0, 0, 200, 0);

            gradient.addColorStop(0, 'red');
            gradient.addColorStop(1, 'blue');

            ctx.fillStyle = gradient;
            ctx.fillRect(10, 10, 200, 100);
          </script>
        </body>
      </html>
    
  

放射状グラデーション:

HTML
    
      <html>
        <head>
          <title>Document</title>
        </head>
        <body>
          <canvas id="myCanvas" width="800" height="600"></canvas>

          <script>
            const canvas = document.getElementById('myCanvas');
            const ctx = canvas.getContext('2d');
            const radialGradient = ctx.createRadialGradient(400, 200, 20, 400, 200, 100);

            radialGradient.addColorStop(0, 'yellow');
            radialGradient.addColorStop(1, 'green');

            ctx.fillStyle = radialGradient;
            ctx.fillRect(300, 100, 200, 200);
          </script>
        </body>
      </html>
    
  

6. 画像

drawImageメソッドは、Canvas上に画像を描画するために使われるよ:

HTML
    
      <html>
        <head>
          <title>Document</title>
        </head>
        <body>
          <canvas id="myCanvas" width="800" height="600"></canvas>

          <script>
            const canvas = document.getElementById('myCanvas');
            const ctx = canvas.getContext('2d');
            const img = new Image();

            img.onload = function() {
              ctx.drawImage(img, 256, 256);
            };

            img.src = 'https://cdn.javarush.com/images/article/ebb06cf3-0e04-45bd-a33e-31fe096fd323/256.jpeg';
          </script>
        </body>
      </html>
    
  
HTML
    
      <html>
        <head>
          <title>Document</title>
        </head>
        <body>
          <canvas id="myCanvas" width="800" height="600"></canvas>

          <script>
            const canvas = document.getElementById('myCanvas');
            const ctx = canvas.getContext('2d');
            const img = new Image();

            img.onload = function() {
              ctx.drawImage(img, 256, 256);
            };

            img.src = 'path/to/image-1.jpg';
          </script>
        </body>
      </html>
    
  

10.3 Canvasでのアニメーション

アニメーションを作成するには、指定した関数を呼び出して新しいアニメーションフレームを描画するためのrequestAnimationFrameメソッドを使うよ。

1. アニメーションの基本

簡単なアニメーションの例:

HTML
    
      <html>
        <head>
          <title>Document</title>
        </head>
        <body>
          <canvas id="myCanvas" width="800" height="600"></canvas>

          <script>
            const canvas = document.getElementById('myCanvas');
            const ctx = canvas.getContext('2d');
            let x = 0;
            let y = 0;

            function animate() {
              ctx.clearRect(0, 0, canvas.width, canvas.height);

              ctx.fillStyle = 'blue';
              ctx.fillRect(x, y, 50, 50);

              x += 2;
              y += 2;

              requestAnimationFrame(animate);
            }

            animate();
          </script>
        </body>
      </html>
    
  

2. 複雑なアニメーション

円アニメーションの例:

HTML
    
      <html>
        <head>
          <title>Document</title>
        </head>
        <body>
          <canvas id="myCanvas" width="800" height="600"></canvas>

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

            let angle = 0;

            function animateCircle() {
              ctx.clearRect(0, 0, canvas.width, canvas.height);

              const centerX = canvas.width / 2;
              const centerY = canvas.height / 2;
              const radius = 50;

              ctx.beginPath();
              ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
              ctx.fillStyle = 'blue';
              ctx.fill();

              ctx.beginPath();
              ctx.arc(centerX + Math.cos(angle) * 100, centerY + Math.sin(angle) * 100, radius, 0, Math.PI * 2);
              ctx.fillStyle = 'red';
              ctx.fill();

              angle += 0.05;

              requestAnimationFrame(animateCircle);
            }

            animateCircle();
          </script>
        </body>
      </html>
    
  

3. タイマーの使用

アニメーションを作成するために、setIntervalsetTimeoutメソッドも使えるよ。

setIntervalを使用したアニメーションの例:

HTML
    
      <html>
        <head>
          <title>Document</title>
        </head>
        <body>
          <canvas id="myCanvas" width="800" height="600"></canvas>

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

            let x = 0;
            let y = 0;

            function draw() {
              ctx.clearRect(0, 0, canvas.width, canvas.height);

              ctx.fillStyle = 'blue';
              ctx.fillRect(x, y, 50, 50);

              x += 2;
              y += 2;
            }

            setInterval(draw, 30);
          </script>
        </body>
      </html>
    
  
1
Опрос
DOMイベント,  42 уровень,  4 лекция
недоступен
DOMイベント
DOMイベント
コメント
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION