Canvas Animation: Creating Beautiful HTML 5 Animations (2024)

Written By Prosper Otemuyiwa

Canvas animation is a feature of HTML5 that allows you to draw images, edit images, and erase them, on a drawing board which you set up with the <canvas> element.

The canvas is a rectangle-like area on an HTML page. By default, the canvas has no border or content.

You can use the HTML5 canvas element to create animations. This is done by combining HTML, CSS, and JavaScript (JS) to build shapes and modify them on the canvas. JavaScript animations are done by programming gradual changes in an element’s style. The changes are called by a timer. When the timer interval is small, the animation looks continuous.

When choosing a canvas size, you should consider where your image or animation will be displayed. For desktop computers, a common choice is 1920×1080 pixels (1080p).

The general process for creating an animation is:

  • Set up a canvas by adding a <canvas> element to your HTML document
  • Locate the element in your JavaScript code and create a drawing object
  • Draw your shapes with a JavaScript method like fillStyle, fillRect, strokeStyle, or strokeRect
  • Clear the canvas using the clearRect method and draw another frame

This article shows you how to follow this process and create simple animations in three examples. Also described are the best practices for canvas optimization, including the procedures for prerendering to an off-screen canvas, batching together canvas calls, layering canvas for complex scenes, and implementing the requestAnimationFrame() method.

Here are the sections:

  • Definition of HTML5 Canvas Animation
  • Process for Creating a Simple HTML5 Canvas Animations
  • Code Examples
  • HTML5 Best Practices for Canvas Optimization
  • Generation of GIF-Based Animations With Cloudinary
  • Display of Video Content With Cloudinary

Definition of HTML5 Canvas Animation

You create HTML5 animations with HTML’s canvas element, which acts as a drawing board for images on which are displayed multiple frames for animation. As mentioned earlier, to build HTML5 animations, you use HTML, CSS, and JS.

Additional tools are available with which you can quickly create complex animations. Examples are media management systems and HTML5-animation software, which offer the drag-and-drop capability for placement of shapes and enable interactivity. HTML5 animation tools typically generate code, which you can then modify or embed in your sites or apps.

Process for Creating a Simple HTML5 Canvas Animations

To create animations with HTML5, you need shapes and a method for controlling the live actions. Recall that you can create shapes, which are JS elements, and control animations with CSS or through JS. You can also incorporate images, video, or audio by importing the appropriate elements.

Follow these steps:

  1. Set up a canvas by adding a <canvas> element to your HTML document, for example:<canvas id="myCanvas" width="300" height="200"></canvas>
  2. Locate the element in your JS and create a drawing object with this code:
    let canvas = document.getElementById("myCanvas");let ctx = canvas.getContext("2d");
  3. Draw your shapes with a method, such as one of the following:
    • fillStyle(color|pattern|gradient): for setting the fill style of your shape.
    • fillRect(x,y,w,h): for drawing a rectangle according to the specified coordinates and fill style.
    • strokeStyle(color|pattern|gradient): for specifying a stroke style for your shape.
    • strokeRect(x,y,w,h): for drawing a rectangle with borders that match the specified sizes, coordinates, and style.
  4. Clear the canvas using the clearRect() method and draw another frame

For all the drawing options, see the W3Schools’ HTML Canvas Reference.

While drawing shapes, you can save your canvas state to create frames for rendering according to the parameters you set with the following JS methods:

  • window.setInterval()
  • window.setTimeout()
  • window.requestAnimationFrame()

HTML5 Canvas Animations with Code Examples

Below are three beautiful examples of HTML5 animations that showcase their types. To see the HTML, CSS, and JS code within each frame, click the buttons across the top left.

  1. Lightning, created by Jack Rugile
  1. Tearable Mesh, created by dissimulate
  1. Earth and Sun, created by MDN

HTML5 Best Practices for Canvas Optimization

For a smooth performance of animations, adopt the best practices below.

Prerender to an Off-Screen Canvas

A majority of the scenes in many animations, such as games, contain repeated images or similar ones. Rather than reloading those images in your primary canvas each time, prerender the scenes in an off-screen canvas, after which you can move that canvas back in line with your primary one.

Such a practice not only boosts the performance of your animations, but also smooths out their appearance.

Batch Together Canvas Calls

Drawing elements while scripting animations takes resources and time. For efficiency, consider loading multiple, shorter commands at once to the video buffer, which then processes each of the operations.

For example:

context.beginPath();for (let i = 0; i < points.length - 1; i++) { let p1 = points[i]; let p2 = points[i+1]; context.moveTo(p1.x, p1.y); context.lineTo(p2.x, p2.y);}context.stroke(); **//Placing this method inside the for loop would result in poorer performance.**

Layer Canvases for Complex Scenes

Layering canvases separates the rendering of larger elements. Do so by applying transparency to your top-layer canvas elements and a background canvas to those elements that you want to render. Assuming that your canvases are aligned, viewers will see a composite image of all the canvases on a rendering of your scene.

With layered canvases, you can keep the static elements of your animation as background and create the moving elements in the other layers, saving you the trouble of having to refresh or rerender a majority of your scene.

Implementation of requestAnimationFrame()

The requestAnimationFrame method enables you to rely on your viewer’s browser to apply your set-rendering routine at the right time. That means that no rendering occurs if your page is not being viewed—as opposed to having the browser render scenes at a fixed rate regardless of whether the viewer is on your page.

Having the browser determine when to render animations eliminates waste of processing power when they are out of view. However, when applying requestAnimationFrame(), be sure to verify that the browser is rendering the animation smoothly. As a rule, with requestAnimationFrame() in place, browsers render animations at 60 FPS, but that’s not guaranteed.

The following code adds a check for smoothness:

let x = 50;let y = 50;let lastRender = Date.now();function render() { let delta = Date.now() - lastRender; x += delta; y += delta; context.fillRect(x, y, W, H); requestAnimationFrame(render);}render();

Generation of GIF-Based Animations With Cloudinary

Generating animated GIFs on Cloudinary is a simple, intuitive process:

  1. Create your images with Cloudinary overlays and chained transformations.
  2. Properly position the images that are in or outside the canvas with custom overlay coordinates.
  3. Add a simple script that programmatically generates transformation URLs and pass them to Cloudinary’s upload API call as the criteria for generating new images.

In Cloudinary, you can create a “sprite”—a single, cloud-based GIF—by merging together images that share the same tag. For a step-by-step tutorial, see our post Create Cloud-Based Animation Sequence GIFs.

Display of Video Content With Cloudinary

Beyond animations, most websites need a convenient way to process and display video. Cloudinary is the answer: it’s a cloud-based platform on which you can dynamically transcode and manipulate videos, optimizing file formats and sizes to any device, browser, or media channel. Additionally, you can easily perform these tasks on that platform:

  • Embed videos in webpages and apps with Cloudinary’s dynamic URLs.
  • Integrate your videos with URL-based APIs and SDKs.
  • Deliver smooth video-streaming through multiple CDNs and live-stream from any device, including sharing on social media.

Why not sign up for a free Cloudinary account to try things out? We offer a generous free plan to get you started.

Want to learn more about image editing?

Have a look at these articles:

  • Image-Editing Basics and a Tutorial for Automation With AI
  • How to Automatically Remove Photo Backgrounds in Seconds With AI
  • Top 7 jQuery Sliders and Three Ways in Which to Create Your Own
  • Adding Image Watermarks, Credits, Badges and Text Overlays to Images
  • Add the 360 Product Viewer to Your Commerce Site with Cloudinary
  • Smart automatic image cropping: Maybe you CAN always get what you want
  • Integrating Cloudinary Into Your Shopify Store
  • How to Overlay Text on Image Easily, Pixel Perfect and With No CSS/HTML
  • Taking Cloudinary’s Magento Extension to the Next Level
Canvas Animation: Creating Beautiful HTML 5 Animations (2024)

FAQs

What is HTML5 canvas in animate? ›

Canvas animation is a feature of HTML5 that allows you to draw images, edit images, and erase them, on a drawing board which you set up with the <canvas> element. The canvas is a rectangle-like area on an HTML page. By default, the canvas has no border or content.

What is a canvas in HTML5? ›

A canvas is a rectangular area on an HTML page. By default, a canvas has no border and no content. Note: Always specify an id attribute (to be referred to in a script), and a width and height attribute to define the size of the canvas. To add a border, use the style attribute.

Which HTML5 element is used to draw graphics on the fly? ›

The HTML <canvas> element is used to draw graphics, on the fly, via scripting (usually JavaScript). The <canvas> element is only a container for graphics.

What is the HTML 5 tag that is used to draw graphics on the fly via scripting usually JavaScript? ›

The <canvas> tag is used to draw graphics, on the fly, via scripting (usually JavaScript). The <canvas> tag is transparent, and is only a container for graphics, you must use a script to actually draw the graphics.

Is HTML5 Canvas still used? ›

The HTML5 canvas has the potential to become a staple of the web, enjoying ubiquitous browser and platform support in addition to widespread webpage support, as nearly 90% of websites have ported to HTML5.

Where is HTML canvas used? ›

The Canvas API provides a means for drawing graphics via JavaScript and the HTML <canvas> element. Among other things, it can be used for animation, game graphics, data visualization, photo manipulation, and real-time video processing.

What are the advantages of HTML5 Canvas? ›

One of the main benefits of using HTML5 canvas for web design is that it gives you more control and flexibility over the graphics. You can create custom charts that suit your needs and style, and you can also add interactivity and animation to them.

Why learn HTML canvas? ›

The canvas element in HTML5 allows you to create amazing dynamic script based drawings and animations directly within your webpages.

What is the difference between HTML and HTML canvas? ›

The <canvas> element on its own is just a bitmap and does not provide information about any drawn objects. Canvas content is not exposed to accessibility tools as semantic HTML is. In general, you should avoid using canvas in an accessible website or app.

How does HTML canvas work? ›

<canvas> is an HTML element which can be used to draw graphics via scripting (usually JavaScript). This can, for instance, be used to draw graphs, combine photos, or create simple animations.

What is the difference between HTML SVG and HTML canvas? ›

Differences Between SVG and Canvas

SVG is a language for describing 2D graphics in XML, while Canvas draws 2D graphics, on the fly (with JavaScript). SVG is XML based, which means that every element is available within the SVG DOM. You can attach JavaScript event handlers to SVG graphics.

What method is used to draw an image or video on a canvas? ›

The drawImage() method draws an image, canvas, or video onto the canvas. The drawImage() method can also draw parts of an image, and/or increase/reduce the image size.

Which HTML tag is used to display a picture in a web page? ›

The <img> tag is used to embed an image in an HTML page.

What is the HTML code that will display an image on a web page? ›

Example
  1. <a href="default.asp">
  2. <img src="smiley.gif" alt="HTML tutorial" style="width:42px;height:42px;">
  3. </a>

Does Adobe animate use HTML5? ›

Animate publishes to HTML5 by leveraging the Canvas API. Animate seamlessly translates objects created on stage in to their Canvas counterparts. By providing a 1-to-1 mapping of Animate features with the APIs within Canvas, Animate enables you to publish complex content to HTML5.

How do you create and publish HTML5 Canvas documents in Animate? ›

To create an HTML5 Canvas document, do the following: Select File > New to display the New Document dialog. Select the Advanced tab from the top of the screen and click the HTML5 Canvas option. This opens a new FLA with Publish Settings modified to produce HTML5 output.

What is SVG and canvas in HTML5? ›

SVG and Canvas are HTML5 APIs for rendering vector and raster graphics, respectively. SVG is used to create vector-based graphics, whereas Canvas can render both vector and raster graphics. Canvas is better for quickly rendering graphics and animations with less control than SVG.

Top Articles
Latest Posts
Article information

Author: Ray Christiansen

Last Updated:

Views: 5649

Rating: 4.9 / 5 (69 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Ray Christiansen

Birthday: 1998-05-04

Address: Apt. 814 34339 Sauer Islands, Hirtheville, GA 02446-8771

Phone: +337636892828

Job: Lead Hospitality Designer

Hobby: Urban exploration, Tai chi, Lockpicking, Fashion, Gunsmithing, Pottery, Geocaching

Introduction: My name is Ray Christiansen, I am a fair, good, cute, gentle, vast, glamorous, excited person who loves writing and wants to share my knowledge and understanding with you.