JSFiddle - React, Tailwind, and code Playground
by Tan
HTML
<canvas id="scene"></canvas>
CSS
body {
margin: 0;
overflow: hidden;
}
canvas {
width:100vw;
height:100vh;
}
JavaScript
console.clear();
// Get the canvas element from the DOM
const canvas = document.getElementById('scene');
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
// Store the 2D context
const ctx = canvas.getContext('2d');
if (window.devicePixelRatio > 1) {
canvas.width = canvas.clientWidth * 2;
canvas.height = canvas.clientHeight * 2;
ctx.scale(2, 2);
}
function getTexture(emoji) {
const tempCanvas = document.createElement("canvas");
const tempCtx = tempCanvas.getContext("2d");
tempCanvas.width = 60;
tempCanvas.height = 60;
tempCtx.textAlign = 'center';
tempCtx.textBaseline = 'middle';
tempCtx.font = '54px serif';
tempCtx.fillText(emoji, 30, 35);
return tempCanvas;
}
const textures = [getTexture('🦊'), getTexture('🦓'), getTexture('🐹'), getTexture('🐨')];
/* ====================== */
/* ====== VARIABLES ===== */
/* ====================== */
let width = canvas.offsetWidth; // Width of the canvas
let height = canvas.offsetHeight; // Height of the canvas
const dots = []; // Every dots in an array
/* ====================== */
/* ====== CONSTANTS ===== */
/* ====================== */
/* Some of those constants may change if the user resizes their screen but I still strongly believe they belong to the Constants part of the variables */
let DOTS_AMOUNT = Math.min(width, height); // Amount of dots on the screen
const DOT_RADIUS = 20; // Radius of the dots
let PROJECTION_CENTER_X = width / 2; // X center of the canvas HTML
let PROJECTION_CENTER_Y = height / 2; // Y center of the canvas HTML
let PERSPECTIVE = width * 0.8;
let GLOBE_RADIUS = Math.min(width, height) * 0.4;
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]
this.texture = textures[Math.floor(Math.random() * textures.length)];
// Calculate the [x, y, z] coordinates of the dot along the globe
this.x = 0;
...