Canvas中的爆炸動畫


在本教程中,我們將學習如何使用 HTML 中的 canvas 建立爆炸動畫效果。使用 canvas,我們可以輕鬆而強大的方式在網頁上繪製圖形。

讓我們看看一些在 canvas 中建立爆炸動畫的示例。

爆炸動畫 1

我們將建立一個由 50 個隨機顏色的粒子組成的爆炸,這些粒子起源於 canvas 的中心並向隨機方向移動。粒子將繼續移動,直到頁面重新整理。

演算法

  • 步驟 1 − 建立一個 HTML canvas 元素,其 id 為“explosion”,並將尺寸設定為 400x400 畫素。

  • 步驟 2 − 初始化一個粒子陣列來儲存粒子物件,以及 canvas 元素的 2D 渲染上下文。

  • 步驟 3 − 定義一個函式 createExplosion( ),它將 50 個粒子物件推送到粒子陣列中。每個粒子物件都具有 x 和 y 位置、半徑、顏色、水平速度和垂直速度的屬性。x 和 y 位置以及顏色設定為隨機值,半徑和速度設定為特定範圍內的隨機數。

  • 步驟 4 − 定義一個函式 draw( ),它清除 canvas 並遍歷粒子陣列,使用其屬性為每個粒子繪製一個圓形。

  • 步驟 5 − 定義一個函式 update( ),它遍歷粒子陣列並根據其速度更新每個粒子的 x 和 y 位置。

  • 步驟 6 − 定義一個函式 animate(),它呼叫 update( ) 和 draw( ) 函式,然後使用 requestAnimationFrame 呼叫自身。

  • 步驟 7 − 呼叫 createExplosion() 函式來初始化粒子陣列。

  • 步驟 8 − 呼叫 animate() 函式以啟動動畫。

示例

在下面的示例中,我們正在建立運動的錯覺。我們不斷更改粒子的屬性,並使用動畫迴圈在 canvas 上持續繪製和更新它。

<html>
<head>
   <style>
      canvas {
         border: 2px solid black;
      }
   </style>
</head>
<body>
   <canvas id="explosion" width="550" height="400"></canvas>
   <script>
      const canvas = document.getElementById('explosion');
      const context = canvas.getContext('2d');
      let particles = [];
      
      // Creates a new particle at the center of the canvas
      function createExplosion() {
         for (let i = 0; i < 50; i++) {
            particles.push({
               x: canvas.width / 2,
               y: canvas.height / 2,
               radius: Math.random() * 3 + 1,
               color: `rgba(${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)})`,
               velocityX: Math.random() * 20 - 10,
               velocityY: Math.random() * 20 - 10
            });
         }
      }
      
      // Renders the particles onto the canvas
      function draw() {
         context.clearRect(0, 0, canvas.width, canvas.height);
         particles.forEach(particle => {
            context.beginPath();
            context.arc(particle.x, particle.y, particle.radius, 0, Math.PI * 2);
            context.fillStyle = particle.color;
            context.fill();
            context.closePath();
         });
      }
      
      // Updates the positions of the particles
      function update() {
         particles.forEach(particle => {
            particle.x += particle.velocityX;
            particle.y += particle.velocityY;
         });
      }
      // The main animation loop
      function animate() {
         update();
         draw();
         requestAnimationFrame(animate);
      }
      createExplosion();
      animate();
   </script>
</body>
</html>

爆炸動畫 2

我們將使用事件監聽器並檢測滑鼠移動。當檢測到 mousemove 事件時,我們將更新滑鼠物件的 x 和 y 位置,並將五個新的粒子物件推送到陣列中。因此,它看起來像一個爆炸。

演算法

  • 步驟 1 − 初始化以下變數 −

    • canvas − 具有 id“mCanvas”的 canvas 元素

    • ctx − canvas 的 2D 渲染上下文

    • particlesArray − 一個空陣列,用於儲存粒子物件

    • hue − 初始化為 0 的變數

  • 步驟 2 − 將 canvas 元素的 heightwidth 分別設定為視窗的內部高度和寬度。

  • 步驟 3 − 向視窗物件新增一個 resize 事件監聽器,以便在調整視窗大小時更新 canvas 元素的高度和寬度。

  • 步驟 4 − 初始化一個滑鼠物件,其屬性 x 和 y 都設定為未定義。

  • 步驟 5 − 定義一個 Particles 類,其中包含以下方法

  • 步驟 5.1constructor() 為每個粒子物件設定以下屬性 −

    • x − 滑鼠物件的當前 x 位置

    • y − 滑鼠物件的當前 y 位置

    • size − 1 到 10 之間的隨機數

    • speedX − -1.5 到 1.5 之間的隨機數

    • speedY − -1.5 到 1.5 之間的隨機數

  • 步驟 5.2 − update(); 此方法分別透過其 speedX 和 speedY 值遞增粒子的 x 和 y 位置。如果粒子的尺寸大於 .3,則將其遞減 .1。

  • 步驟 5.3 − draw(); 此方法使用色相值將 ctx 物件的填充樣式設定為 HSL(色相、飽和度、亮度)顏色空間中的顏色,並使用粒子的 x 和 y 位置作為中心,其尺寸作為半徑填充圓形路徑。

  • 步驟 6 − 定義一個 handleParticles() 函式來遍歷 particlesArray。對於陣列中的每個粒子,呼叫其 update 和 draw 方法。如果粒子的尺寸變為小於或等於 .3,則將其從陣列中刪除。

  • 步驟 7 − 定義一個 animate() 函式來用半透明黑色矩形填充 canvas 元素,處理 particlesArray 中的粒子,並遞增色相值。

  • 步驟 8 − 使用 requestAnimationFrame 呼叫 animate() 函式。

  • 步驟 9 − 向 canvas 元素新增一個 mousemove 事件監聽器。當檢測到 mousemove 事件時,更新滑鼠物件的 x 和 y 屬性,並將五個新的粒子物件推送到 particlesArray 中。

示例

在下面的示例中,我們將建立一個爆炸動畫,只要滑鼠移動就會執行。我們可以使用事件監聽器來實現這一點。

<html>
<head>
   <style>
      body {
         padding: 0;
         margin: 0;
         box-sizing: border-box;
         background: #000;
      }
      #mCanvas{
         height: 100%;
         width: 100%;
         position: absolute;
         top: 0;
         left: 0;
         background: #000;
      }
   </style>
</head>
<body>
   <canvas id="mCanvas"></canvas>
   <script>
      const canvas = document.getElementById('mCanvas');
      const ctx = canvas.getContext('2d');
      const particlesArray = [];
      let hue = 0;
      canvas.height = window.innerHeight;
      canvas.width = window.innerWidth;
      window.addEventListener('resize', function(){
         canvas.height = window.innerHeight;
         canvas.width = window.innerWidth;
      })
      const mouse = {
         x: undefined,
         y: undefined
      }
      class Particles{
         constructor(){
            this.x = mouse.x;
            this.y = mouse.y;
            this.size = Math.random()*10 + 1;
            this.speedX = Math.random()*3 - 1.5;
            this.speedY = Math.random()*3 - 1.5;
         }
         update(){
            this.x += this.speedX;
            this.y += this.speedY;
            if(this.size > .3){
               this.size -= .1;
            }
         }
         draw(){
            ctx.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
            ctx.fill();
         }
      } // end Particle
      function handleParticles(){
         for(let i=0 ; i<particlesArray.length ; i++){
            particlesArray[i].update();
            particlesArray[i].draw();
            if(particlesArray[i].size <= .3){
               particlesArray.splice(i, 1);
               i--;
            }
         }
      } // end of function
      function animate(){
         ctx.fillStyle = 'rgba(0,0,0, .1)';
         ctx.fillRect(0, 0, canvas.width, canvas.height);
         handleParticles();
         hue++;
         requestAnimationFrame(animate);
      }
      animate();
      canvas.addEventListener('mousemove', function(event){
         mouse.x = event.x;
         mouse.y = event.y;
         for(let i=0 ; i<5 ; i++){
            particlesArray.push(new Particles());
         }
      })
   </script>
</body>
</html>

我們使用 canvas 元素建立了一個爆炸效果。當滑鼠移到 canvas 上時,頁面會建立新的粒子物件並將其新增到陣列中。粒子具有隨機的位置、大小和速度,並使用隨時間變化的色相值在 canvas 上繪製。粒子在移動時會縮小,並且當它們的大小變得足夠小時會從陣列中刪除。canvas 使用 requestAnimationFrame 函式持續重新繪製,以建立動畫效果。頁面還在調整視窗大小時更新 canvas 元素的尺寸。

我們已經學習瞭如何在 canvas 中建立不同的爆炸動畫效果。

更新於: 2023-03-17

957 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.