Canvas API

Frontend SELF ZH
第 42 级 , 课程 4
可用

10.1 Canvas的基础操作

Canvas API 给开发者提供了很多很酷的工具,用来在web应用里搞二维图形和动画。在这节课,我们会看看Canvas API的基础,包括创建元素,绘制图形和制作动画。

创建 <canvas> 元素

HTML里的 <canvas> 元素是用来创建绘图区域的,你可以在这里搞各种图形操作:

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

获取绘图上下文

想在 <canvas> 元素上动手,就得先拿到绘图上下文。二维图形用的是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