As we were exploring options on how to best illustrate a brand story recently, we came up with a pretty interesting prototype: a multi-step animation that starts with a rotating globe full of particles.
From a technical perspective, that first step was definitely the most interesting one. Because as all the following animation steps were plain 2D, I couldn’t use a 3D renderer such as Three.js. And so I had to figure out how to render a 3D shape using only the Canvas 2D API.
In this article, I’ll show you how I finally did it. I’ll first explain how to render a basic shape from a 3D scene using the JavaScript Canvas 2D API. Then in the second part of this post, I’ll show you how to make everything a bit fancier with some textures and 3D volumes.
1. Setup the canvas scene
To get started, we need to add a canvas element in our HTML. We also need to add an id so it will be easier to select it from JavaScript. That’s all we need in the HTML!
| <canvas id="scene"></canvas> |
For the CSS, we need to remove the default margins on the body and prevent scrollbars from appearing by using ‘overflow: hidden;’. Because we want our canvas to be full screen, we define its width and height at 100% of the viewport.
| body { | |
| margin: 0; | |
| overflow: hidden; | |
| } | |
| canvas { | |
| width:100vw; | |
| height:100vh; | |
| } |
To setup a full screen Canvas demo in JavaScript, we need to select the canvas from the DOM and get its dimensions. The rest of the setup is mostly about handling the user resizing their screen.
| // Get the canvas element from the DOM | |
| const canvas = document.getElementById('scene'); | |
| // Get the canvas dimensions | |
| let width = canvas.offsetWidth; // Width of the scene | |
| let height = canvas.offsetHeight; // Height of the scene | |
| // Store the 2D context | |
| const ctx = canvas.getContext('2d'); | |
| // Function called right after user resized its screen | |
| function onResize () { | |
| // We need to define the dimensions of the canvas to our canvas element | |
| // Javascript doesn't know the computed dimensions from CSS so we need to do it manually | |
| width = canvas.offsetWidth; | |
| height = canvas.offsetHeight; | |
| // If the screen device has a pixel ratio over 1 | |
| // We render the canvas twice bigger to make it sharper (e.g. Retina iPhone) | |
| if (window.devicePixelRatio > 1) { | |
| canvas.width = canvas.clientWidth * 2; | |
| canvas.height = canvas.clientHeight * 2; | |
| ctx.scale(2, 2); | |
| } else { | |
| canvas.width = width; | |
| canvas.height = height; | |
| } | |
| } | |
| // Listen to resize events | |
| window.addEventListener('resize', onResize); | |
| // Make sure the canvas size is perfect | |
| onResize(); |
2. Create particles
To easily manage a high number of particles in JavaScript, the easiest way is by using a class (introduced with ECMAScript 2015). This will allow us to define random properties for every particle while still sharing common methods between all of them.
The first part of a class is the constructor method and we use it to store the custom properties of each particle. We also create two methods for our dots: project() and draw(). The project method is were the magic happens: we convert the 3D coordinates of our particle to a 2D world. Finally, the draw method is where we draw the particle on our canvas after we calculate the projected values.
| let PERSPECTIVE = width * 0.8; // The field of view of our 3D scene | |
| let PROJECTION_CENTER_X = width / 2; // x center of the canvas | |
| let PROJECTION_CENTER_Y = height / 2; // y center of the canvas | |
| const dots = []; // Store every particle in this array | |
| class Dot { | |
| constructor() { | |
| this.x = (Math.random() - 0.5) * width; // Give a random x position | |
| this.y = (Math.random() - 0.5) * height; // Give a random y position | |
| this.z = Math.random() * width; // Give a random z position | |
| this.radius = 10; // Size of our element in the 3D world | |
| this.xProjected = 0; // x coordinate on the 2D world | |
| this.yProjected = 0; // y coordinate on the 2D world | |
| this.scaleProjected = 0; // Scale of the element on the 2D world (further = smaller) | |
| } | |
| // Project our element from its 3D world to the 2D canvas | |
| project() { | |
| // The scaleProjected will store the scale of the element based on its distance from the 'camera' | |
| this.scaleProjected = PERSPECTIVE / (PERSPECTIVE + this.z); | |
| // The xProjected is the x position on the 2D world | |
| this.xProjected = (this.x * this.scaleProjected) + PROJECTION_CENTER_X; | |
| // The yProjected is the y position on the 2D world | |
| this.yProjected = (this.y * this.scaleProjected) + PROJECTION_CENTER_Y; | |
| } | |
| // Draw the dot on the canvas | |
| draw() { | |
| // We first calculate the projected values of our dot | |
| this.project(); | |
| // We define the opacity of our element based on its distance | |
| ctx.globalAlpha = Math.abs(1 - this.z / width); | |
| // We draw a rectangle based on the projected coordinates and scale | |
| ctx.fillRect(this.xProjected - this.radius, this.yProjected - this.radius, this.radius * 2 * this.scaleProjected, this.radius * 2 * this.scaleProjected); | |
| } | |
| } | |
| // Create 800 new dots | |
| for (let i = 0; i < 800; i++) { | |
| // Create a new dot and push it into the array | |
| dots.push(new Dot()); | |
| } |
You may have noticed we are using a PERSPECTIVE constant. This value will define the behavior of the ‘camera’ we are simulating in the project method. If you increase its value, you will notice that the perspective is getting less and less visible, everything will look flat. If you do the opposite and lower the value, the perspective will be much more intense.
3. Render the scene
Now that we have all our particles ready to be rendered on the screen, we need to create a small function that loops through all the dots and renders them on the canvas.
| function render() { | |
| // Clear the scene from top left to bottom right | |
| ctx.clearRect(0, 0, width, height); | |
| // Loop through the dots array and draw every dot | |
| for (var i = 0; i < dots.length; i++) { | |
| dots[i].draw(); | |
| } | |
| // Request the browser the call render once its ready for a new frame | |
| window.requestAnimationFrame(render); | |
| } |
If you try the code as is, you will get something very static because we are not moving the dots in our 3D scene.
| class Dot { | |
| constructor() { | |
| ... | |
| TweenMax.to(this, (Math.random() * 10 + 15), { | |
| z: width, | |
| repeat: -1, | |
| yoyo: true, | |
| ease: Power2.easeOut, | |
| yoyoEase: true, | |
| delay: Math.random() * -25 | |
| }); | |
| } | |
| ... | |
| } |
You may think it is not that interesting to write so much for so little. We could get away with simulating the complex math. But, now that the hard part is done, we can go crazy!
Making a globe
To create a globe out of particles, we need to calculate their coordinates on its surface. The coordinates of a point along a sphere don’t use the classic Cartesian Coordinates (x, y, z) but three different values from the Polar Coordinate System:
- Radius: The radius of the sphere
- Theta: The polar angle (between 0 and 360°)
- Phi: The azimuth angle (between -90° and 90°)
In our case we want random values for every dot, so we will define the Theta and Phi values randomly when we create a new one. The radius being the same for every dot we can store in into a global variable.
| let GLOBE_RADIUS = width / 3; // Radius of the globe based on the canvas width | |
| class Dot { | |
| constructor() { | |
| this.theta = Math.random() * 2 * Math.PI; // Random value between [0, 2Pi] | |
| this.phi = Math.acos((Math.random() * 2) - 1); // Random value between [0, Pi] | |
| } | |
| ... | |
| } |
You may be wondering why we are not using a more basic way to generate a random value for Phi. If we were to do so, the distribution along the sphere wouldn’t be uniform and would display more particles around the poles. This is why we are using using an Arc Cosine (acos) function to fix this issue.
Finally we need to convert the coordinates from Polar to Cartesian to match our current 3D world every time we want to project the dot on the 2D canvas. We are also drawing it using a circle this time, instead of a rectangle.
| const DOT_RADIUS = 10; // Radius of the dots | |
| let GLOBE_RADIUS = width / 3; // Radius of the globe based on the canvas width | |
| class Dot { | |
| constructor() { | |
| this.theta = Math.random() * 2 * Math.PI; // Random value between [0, 2Pi] | |
| this.phi = Math.acos((Math.random() * 2) - 1); // Random value between [0, Pi] | |
| // The x, y, z coordinates will be calculated in the project() function | |
| this.x = 0; | |
| this.y = 0; | |
| this.z = 0; | |
| // The projected coordinates will be calculated in the project() function | |
| this.xProjected = 0; | |
| this.yProjected = 0; | |
| this.scaleProjected = 0; | |
| // Add some animation to the sphere rotate | |
| TweenMax.to(this, 20 + Math.random() * 10, { | |
| theta: this.theta + Math.PI * 2, | |
| repeat: -1, | |
| ease: Power0.easeNone | |
| }); | |
| } | |
| // Project our element from its 3D world to the 2D canvas | |
| project() { | |
| // Calculate the x, y, z coordinates in the 3D world | |
| this.x = GLOBE_RADIUS * Math.sin(this.phi) * Math.cos(this.theta); | |
| this.y = GLOBE_RADIUS * Math.cos(this.phi); | |
| this.z = GLOBE_RADIUS * Math.sin(this.phi) * Math.sin(this.theta) + GLOBE_RADIUS; | |
| // Project the 3D coordinates to the 2D canvas | |
| this.scaleProjected = PERSPECTIVE / (PERSPECTIVE + this.z); | |
| this.xProjected = (this.x * this.scaleProjected) + PROJECTION_CENTER_X; | |
| this.yProjected = (this.y * this.scaleProjected) + PROJECTION_CENTER_Y; | |
| } | |
| // Draw the dot on the canvas | |
| draw() { | |
| // We first calculate the projected values of our dot | |
| this.project(); | |
| // We define the opacity of our element based on its distance | |
| ctx.globalAlpha = Math.abs(1 - this.z / width); | |
| // In this case we are drawing a circle instead of a rectangle | |
| ctx.beginPath(); | |
| // The arc function takes 5 parameters (x, y, radius, angle start, angle end) | |
| ctx.arc(this.xProjected, this.yProjected, DOT_RADIUS * this.scaleProjected, 0, Math.PI * 2); | |
| // Fill the circle in black | |
| ctx.fill(); | |
| } | |
| } |
Depth sorting
So far we have only used a basic monochrome shape from the Canvas
API. If we want to use a custom texture for our particles, we face a
problem.
In the render function we are drawing the particles based on their order in the dots
array. When we use textures it will become noticeable that we are
drawing particles on top of others, without taking their depth value
into account. This will create a weird result with further particles
being displayed over closer ones.
To fix this issue, we need to sort the array of dots based on their Z position right before we draw them so the furthest dots will be drawn first and the closest ones last. We call this method Depth Sorting!
| function render(a) { | |
| ... | |
| // Loop through the dots array and project every dot | |
| for (let i = 0; i < dots.length; i++) { | |
| dots[i].project(); | |
| } | |
| // Sort dots array based on their projected size | |
| dots.sort((dot1, dot2) => { | |
| return dot1.sizeProjection - dot2.sizeProjection; | |
| }); | |
| // Loop through the dots array and draw every dot | |
| for (let i = 0; i < dots.length; i++) { | |
| dots[i].draw(); | |
| } | |
| ... | |
| } |
Rendering 3D volumes
Let’s get really crazy and see if we can render more than just flat shapes with our script! (Spoiler alert: we can) If we think of a cube as data, we can decompose its construction in two parts: 8 vertices and 12 lines.
With that information, we can set two variables in our script to store this data.
- The first variable contains the coordinates of every vertex of cube.
- The second variable is an array of 12 pairs of vertices stored by their index.
We will use this second variable to draw the lines based on those pairs. For example the first pair [0, 1] means that we connect the vertex[0] to the vertex[1].
| const CUBE_VERTICES = [[-1, -1, -1],[1, -1, -1],[-1, 1, -1],[1, 1, -1],[-1, -1, 1],[1, -1, 1],[-1, 1, 1],[1, 1, 1]]; | |
| const CUBE_LINES = [[0, 1], [1, 3], [3, 2], [2, 0], [2, 6], [3, 7], [0, 4], [1, 5], [6, 7], [6, 4], [7, 5], [4, 5]]; |
From those two variables we can generate random cubes in our scene and start animating them by moving the vertices in our 3D world.
You could go even further and draw the faces of the cubes instead of their edges. To do so you will need to know what vertices must be connected for every face and check what faces must be drawn first.
—
Do not hesitate to fork any demo and explore more crazy ideas! If you have any question or remark about this article, do not hesitate to ping me on Twitter @Mamboleoo or go check my work on Instagram.
Cheers 🦊🦓🐹🐨
Louis