Back to all resources
HTML5 Canvas
Animation
American Flag

Animated American Flag

By Jared Malan
This JavaScript code snippet is designed to render and animate an American flag on an HTML canvas element. The code is divided into several key functions:

  1. drawAmericanFlag(canvas, width, padX, padY): This function draws the American flag on the specified canvas. It accepts parameters for the canvas element, the width of the flag, and optional padding values (padX, padY). The flag consists of 13 stripes and a blue rectangle with 50 white stars.
  2. drawStar(ctx, cx, cy, spikes, outerRadius, innerRadius): This helper function is used within drawAmericanFlag to draw individual stars. It takes parameters for the drawing context, the center coordinates of the star, the number of spikes, and the outer and inner radii of the star.
  3. waveFlag(canvas, wavelength, amplitude, period, shading, squeeze): This function animates the flag to create a waving effect. It takes parameters for the canvas, wavelength, amplitude, period, shading intensity, and squeeze effect. The function uses a sine wave to simulate the waving and updates the canvas at a rate determined by the frames per second (fps).

Additionally, the code sets the style of the canvas to center the flag based on its calculated width and height. It also initializes the waving animation using the waveFlag function with specified parameters for the animation's characteristics.

Thanks Mark for the initial code: https://codepen.io/mark_sottek/pen/mJRGyV