Canvas API

Frontend SELF PL
Poziom 42 , Lekcja 4
Dostępny

10.1 Podstawy pracy z Canvas

Canvas API daje developerom super narzędzia do tworzenia grafiki 2D i animacji w aplikacjach webowych. Na tym wykładzie przejdziemy przez podstawy pracy z Canvas API, w tym tworzenie elementów, rysowanie grafiki i tworzenie animacji.

Tworzenie elementu <canvas>

Element <canvas> w HTML-u jest używany do tworzenia obszaru rysowania, na którym można wykonywać różne operacje graficzne:

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

Uzyskiwanie kontekstu rysowania

Aby wykonywać operacje rysowania na elemencie <canvas>, musisz uzyskać kontekst rysowania. Do grafiki 2D używa się kontekstu 2d:

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

10.2 Rysowanie na Canvas

1. Prostokąty

Canvas API oferuje metody do rysowania wypełnionych i obrysowanych prostokątów.

Wypełniony prostokąt — 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>
    
  

Obrys prostokąta — 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>
    
  

Czyszczenie obszaru

Metoda clearRect służy do czyszczenia określonego obszaru:

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. Linie

Do rysowania linii używa się metody beginPath do rozpoczęcia nowej ścieżki oraz metod moveTo i lineTo do określenia współrzędnych linii:

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. Koła i łuki

Metoda arc jest używana do rysowania kół i łuków:

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. Tekst

Metody fillText i strokeText są używane do rysowania tekstu:

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. Gradienty

Canvas API wspiera tworzenie gradientów liniowych i radialnych.

Gradient liniowy:

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>
    
  

Gradient radialny:

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. Obrazy

Metoda drawImage jest używana do rysowania obrazów na 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 Animacje na Canvas

Do tworzenia animacji używa się metody requestAnimationFrame, która wywołuje podaną funkcję do rysowania nowej klatki animacji.

1. Podstawy animacji

Przykład prostej animacji:

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. Złożone animacje

Przykład animacji koła:

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. Użycie timerów

Do tworzenia animacji można również używać metod setInterval i setTimeout.

Przykład animacji z użyciem 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
Ankieta/quiz
DOM-zdarzenia, poziom 42, lekcja 4
Niedostępny
DOM-zdarzenia
DOM-zdarzenia
Komentarze
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION