Skip to content

Instantly share code, notes, and snippets.

@Mamboleoo
Last active April 23, 2021 21:51
Show Gist options
  • Save Mamboleoo/94c16834916bc99a2c65fd94551436d5 to your computer and use it in GitHub Desktop.
Save Mamboleoo/94c16834916bc99a2c65fd94551436d5 to your computer and use it in GitHub Desktop.
Dot class [2D-3D]
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());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment