Happy Birthday Third Part Animations

Robin 🎭 - Feb 17 - - Dev Community

In this article, we’ll delve into how to create a visually engaging and interactive fireworks and balloon animation using HTML5 Canvas and JavaScript. The code outlined here provides an exciting way to implement interactive elements on a webpage, offering insights into animations, particle systems, and physics principles.

We'll walk through the logic and key components of the code and explore how to build a fireworks display and a balloon animation. By the end of this article, you'll understand how to integrate these animations into your own web projects and create a fun, immersive user experience.

1. Understanding HTML5 Canvas and its Role in Web Animations

What is HTML5 Canvas?
HTML5 Canvas is a powerful feature in modern web development that enables developers to draw graphics directly within the browser. With just a few lines of code, you can create complex visuals like charts, games, and animations.

The Importance of Canvas in Animation:
Canvas offers a flexible approach to creating dynamic graphics, allowing developers to access pixel data, render images, and animate objects in real-time. In this article, we'll see how it provides a canvas for drawing and animating fireworks and balloons.


2. Introduction to JavaScript and Its Role in Animating the Canvas

JavaScript plays a pivotal role in handling the animation logic for the canvas. We will explore how JavaScript interacts with the Canvas API to create and control animations.

  • Canvas Context:
    The first step in using the Canvas element is accessing the 2D context. This context is responsible for drawing on the canvas, such as filling shapes, creating paths, and drawing text.

  • Animation with RequestAnimationFrame:
    The requestAnimationFrame() method is essential for creating smooth animations. By repeatedly calling this function, we can create the illusion of continuous movement and make the animation frame rate match the refresh rate of the display.


3. Step-by-Step Breakdown of the Code

HTML Structure:
The HTML part of the code contains the basic structure, including the canvas element and the paragraph that displays information at the bottom of the screen. The canvas serves as the container for all the animated objects, and the paragraph provides information about the creator and project.

<canvas id="c"></canvas>
<p>From the codepals to <a href="#">ST</a><span>, by <a href="https://www.linkedin.com/in/robin-ivi/">Robin</a></span></p>
<script data-name="BMC-Widget" data-cfasync="false" src="https://cdnjs.buymeacoffee.com/1.0.0/widget.prod.min.js" data-id="er.robin" data-description="Support me on Buy me a coffee!" data-message="" data-color="#BD5FFF" data-position="Right" data-x_margin="18" data-y_margin="18"></script>
Enter fullscreen mode Exit fullscreen mode

The canvas element is dynamically sized using JavaScript, taking up the full browser window, ensuring a responsive design. The <p> element includes a link to Robin’s LinkedIn profile and additional elements that contribute to the page's branding.

CSS Styles:
The CSS provides essential layout and style for the canvas and text elements. Key properties include:

  • position: absolute; ensures the canvas fills the entire screen.
  • The paragraph styling, particularly the position: absolute; and font-size: 16px;, places the text at the bottom of the page.

Canvas Variables:

var w = c.width = window.innerWidth,
    h = c.height = window.innerHeight,
    ctx = c.getContext('2d'),
    hw = w / 2,
    hh = h / 2,
    opts = {
        strings: ['HAPPY', 'BIRTHDAY!', 'My Life'],
        charSize: 30,
        charSpacing: 35,
        lineHeight: 40,
        cx: w / 2,
        cy: h / 2,
        fireworkPrevPoints: 10,
        fireworkBaseLineWidth: 5,
        fireworkAddedLineWidth: 8,
        fireworkSpawnTime: 200,
        fireworkBaseReachTime: 30,
        fireworkAddedReachTime: 30,
        fireworkCircleBaseSize: 20,
        fireworkCircleAddedSize: 10,
        fireworkCircleBaseTime: 30,
        fireworkCircleAddedTime: 30,
        fireworkCircleFadeBaseTime: 10,
        fireworkCircleFadeAddedTime: 5,
        fireworkBaseShards: 5,
        fireworkAddedShards: 5,
        fireworkShardPrevPoints: 3,
        fireworkShardBaseVel: 4,
        fireworkShardAddedVel: 2,
        fireworkShardBaseSize: 3,
        fireworkShardAddedSize: 3,
        gravity: 0.1,
        upFlow: -0.1,
        letterContemplatingWaitTime: 360,
        balloonSpawnTime: 20,
        balloonBaseInflateTime: 10,
        balloonAddedInflateTime: 10,
        balloonBaseSize: 20,
        balloonAddedSize: 20,
        balloonBaseVel: 0.4,
        balloonAddedVel: 0.4,
        balloonBaseRadian: -(Math.PI / 2 - 0.5),
        balloonAddedRadian: -1
    },
    calc = {
        totalWidth: opts.charSpacing * Math.max(opts.strings[0].length, opts.strings[1].length)
    },
    Tau = Math.PI * 2,
    TauQuarter = Tau / 4,
    letters = [];
Enter fullscreen mode Exit fullscreen mode

In this code, we define several variables that control various aspects of the animation. These variables include dimensions, settings for text and fireworks, and particle system configurations. We'll look into how these variables control the dynamics of the fireworks and balloon animations.


4. Fireworks Animation Explained

The Firework Effect:
The fireworks effect is created using physics principles. The Letter object has several properties such as x, y, dx, dy, which determine the position and movement of each letter in the fireworks. The fireworks are composed of lines and circles that gradually change over time.

  • Firework Phase:
    The fireworks animation follows a multi-phase process: spawning, reaching a peak, and dispersing in the form of firework shards and fading circles. This progression uses timing-based transitions, often based on the sin() function, to achieve smooth visual effects.

  • Creating Firework Shards:
    After the letter reaches the peak of its movement, it explodes into multiple shards. Each shard is an object that travels in different directions with varying speeds.

  • Shards and Gravity:
    Each shard is affected by gravity, causing it to fall over time. The gravity variable adds this realistic effect to the shards.


5. Balloon Animation

The Balloon Effect:
The balloon animation follows a similar logic to the fireworks, except it involves objects that move upward, inflate, and fade away.

  • Balloon Inflating:
    The balloons initially spawn and gradually inflate as they rise. This effect is achieved by modifying the size of the balloon over time. The inflateTime controls how fast the balloon inflates.

  • Upward Movement:
    Once the balloon is fully inflated, it begins its upward journey, propelled by a random velocity that is based on physics calculations.


6. Shard and Balloon Pathing

Both the firework shards and balloons follow paths that are influenced by velocities and forces. We use trigonometry (Math.cos, Math.sin) to generate directions and speeds for the movement of these objects, allowing them to follow curved paths, creating more dynamic and unpredictable animations.


7. Optimization and Performance Considerations

  • Managing Frame Rate:
    The requestAnimationFrame() function ensures that the animations run smoothly without unnecessary frame drops, adapting to the display refresh rate.

  • Memory Management:
    To maintain performance, we make sure to remove objects that are no longer visible or relevant, such as firework shards and balloons that have drifted off-screen.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .