Skip to content

Instantly share code, notes, and snippets.

@phuctvt
Created January 31, 2020 14:12
Show Gist options
  • Save phuctvt/a00b7ca7782fdb0cd1013d3a617814a6 to your computer and use it in GitHub Desktop.
Save phuctvt/a00b7ca7782fdb0cd1013d3a617814a6 to your computer and use it in GitHub Desktop.
Snow
<!DOCTYPE html>
<html>
<head>
<title>Snow</title>
</head>
<body style="margin: 0;">
<canvas id="canvas"></canvas>
<script type="text/javascript" src="tool.js"></script>
<script type="text/javascript" src="vector.js"></script>
<script type="text/javascript" src="snow.js"></script>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
let c, ctx, w, h;
let snows = [];
let nOfSnows = 150;
let gravity;
function setup() {
c = document.querySelector('#canvas');
c.width = window.innerWidth;
c.height = window.innerHeight;
ctx = c.getContext('2d');
w = c.width;
h = c.height;
for (let i = 0; i < nOfSnows; i++) {
let snow = new Snow(random(0, w), random(0, h));
snows.push(snow);
}
}
function draw() {
ctx.fillStyle = 'rgb(70, 0, 0)';
ctx.fillRect(0, 0, w, h);
for (let snow of snows) {
snow.fall();
snow.draw(ctx);
}
window.requestAnimationFrame(draw);
}
setup();
window.requestAnimationFrame(draw);
class Snow {
constructor(x, y) {
this.pos = new Vector(x, y);
this.r = random(10, 30) * 0.1;
this.vel = new Vector(random(3, 10) * 0.1, random(5, 10) * 0.1);
this.isSimple = !!random(0, 1);
this.img = new Image();
this.img.src = 'snowflake.png';
this.snowSize = random(5, 10);
}
fall() {
this.pos.add(this.vel);
if (this.pos.x > w) this.pos.x = 0;
if (this.pos.y > h) this.pos.y = 0;
}
draw(ctx) {
if (this.isSimple) {
ctx.save();
ctx.beginPath();
ctx.arc(this.pos.x, this.pos.y, this.r, 0, Math.PI * 2);
ctx.fillStyle = 'white';
ctx.fill();
ctx.restore();
} else {
ctx.save();
ctx.drawImage(this.img, this.pos.x, this.pos.y, this.snowSize, this.snowSize);
ctx.restore();
}
}
}
function random(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; //The maximum is inclusive and the minimum is inclusive
}
class Vector {
constructor(x, y) {
this.x = x;
this.y = y;
}
add(vec) {
this.x += vec.x;
this.y += vec.y;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment