The Ultimate WebGL & Canvas Performance Guide

Building beautiful, generative animations using <canvas> and WebGL is easier than ever. The true challenge lies in making sure those complex scenes don’t completely lock up the user’s main thread and drain their battery life in minutes.

HTMLHub specializes in high-performance web animations. While exploring an Abstract Particle System, it’s vital to ensure it remains lightweight.

Here is our ultimate guide to squeezing every drop of performance out of the browser.

1. Avoid Off-Screen Rendering

Always cull your particles. If a floating orb in your generic Particle Swarm travels beyond the bounds of your window.innerWidth and window.innerHeight, immediately stop calculating its physics math or reassign its coordinates to the opposite side of the screen.

// A simple out-of-bounds wrap check
if (particle.x > canvas.width) particle.x = 0;
if (particle.x < 0) particle.x = canvas.width;
if (particle.y > canvas.height) particle.y = 0;
if (particle.y < 0) particle.y = canvas.height;

2. Reduce Costly Context State Changes

When drawing on a 2D Canvas context, changing the ctx.fillStyle or ctx.globalAlpha in the middle of a requestAnimationFrame loop is one of the most expensive operations you can perform.

If you are rendering a Particle Collision Reaction where particles change colors, group the rendering by color instead of by mathematical proximity. Change the stroke or fill style once, draw all particles of that type using ctx.beginPath() and ctx.fill(), then move to the next color.

3. Limit the Array Size

It can be incredibly tempting to crank particle counts into the thousands. But calculating the Math.hypot(dx, dy) distance between 1,000 interacting particles every 16ms scales exponentially ($O(n^2)$ time complexity).

4. Only Animate When Visible

The single most powerful optimization available is the IntersectionObserver. You should never, under any circumstances, fire a requestAnimationFrame when the canvas is scrolled out of view!

All animations in the HTMLHub library natively pause their update loops the second they leave the viewport.

Using these optimization tricks, you can push the boundaries of creative web development while remaining performant and accessible for all users. Explore the optimized effects in the HTMLHub Library.

Source Code
Source Copied!
Loved this effect? Host your deployment globally for free on our partner networks:
Vercel Netlify Hostinger