JSFiddle - React, Tailwind, and code Playground
by colemande
HTML
<canvas id="canvas" width="500" height="500"></canvas> <br/>
Frame Rate: <span id="frame"></span>
CSS
/*Simple reset*/
* {margin: 0; padding: 0;}
body {
/*You can use any kind of background here.*/
background: #6b92b9;
color:white;
}
#canvas {
width:500px;
height:500px;
border:1px solid black;
}
JavaScript
//canvas init
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var fps = document.getElementById('frame');
var frames = 0;
var delta = 0;
//canvas dimensions
canvas.width = 1500;
canvas.height = 1500;
//snowflake particles
var mp = 10000; //max particles
var particles = [];
for(var i = 0; i < mp; i++)
{
particles.push({
x: Math.random()*canvas.width, //x-coordinate
y: Math.random()*canvas.height, //y-coordinate
r: Math.random()*4+1, //radius
d: Math.random()*mp //density
})
}
//Lets draw the flakes
function draw()
{
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "rgba(255, 255, 255, 0.8)";
ctx.beginPath();
for(var i = 0; i < mp; i++)
{
var p = particles[i];
ctx.fillRect(p.x,p.y,4,4);
}
ctx.fill();
}
function frameFnc(){
frames++;
if(new Date().getTime() - delta > 1000){
delta = new Date().getTime();
fps.innerHTML = frames;
frames = 0;
}
}
//Function to move the snowflakes
//angle will be an ongoing incremental flag. Sin and Cos functions will be applied to it to create vertical and horizontal movements of the flakes
var angle = 0;
function update()
{
angle += 0.01;
for(var i = 0; i < mp; i++)
{
var p = particles[i];
p.y += Math.cos(angle+p.d) + 1 + p.r/2;
p.x += Math.sin(angle) * 2;
//Sending flakes back from the top when it exits
//Lets make it a bit more organic and let flakes enter from the left and right also.
if(p.x > canvas.width+5 || p.x < -5 || p.y > canvas.height)
{
if(i%3 > 0) //66.67% of the flakes
{
particles[i] = {x: Math.random()*canvas.width, y: -10, r: p.r, d: p.d};
}
else
{
//If the flake is exitting from the right
if(Math.sin(angle) > 0)
{
//Enter from the left
particles[i] = {x: -5, y: Math.random()*canvas.height, r: p.r, d:...