Skip to content

Commit 5325cb0

Browse files
committed
Pooling snowflakes
Conflicts: www/static/js/snow.js Conflicts: www/static/js/snow.js
1 parent f8c310f commit 5325cb0

File tree

1 file changed

+20
-7
lines changed

1 file changed

+20
-7
lines changed

www/static/js/snow.js

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,14 @@
77
var html = document.documentElement;
88

99
function Snowflake(maxX) {
10+
this.reset(maxX);
11+
}
12+
Snowflake.prototype.tick = function() {
13+
var sidePhase = this.sidePhase += this.sideVel;
14+
this.y += this.vel;
15+
this.x = this.midX + Math.sin(sidePhase) * this.sideAmp;
16+
};
17+
Snowflake.prototype.reset = function(maxX) {
1018
var rand = Math.random();
1119
var sizeRand;
1220
var chanceOfLargeSnowflake = 0.15;
@@ -30,11 +38,10 @@
3038
this.sidePhase = 0;
3139
this.sideAmp = sizeRand * 40;
3240
this.sideVel = Math.random() * 0.05;
33-
}
34-
Snowflake.prototype.tick = function() {
35-
var sidePhase = this.sidePhase += this.sideVel;
36-
this.y += this.vel;
37-
this.x = this.midX + Math.sin(sidePhase) * this.sideAmp;
41+
42+
this.x = 0;
43+
44+
return this;
3845
};
3946

4047
(function() {
@@ -50,6 +57,7 @@
5057
var PIx2 = Math.PI*2;
5158
var assumedFps = 60;
5259
var settlePoint;
60+
var snowflakePool = [];
5361

5462
function resizeCanvas() {
5563
settlePoint = Array(html.clientWidth);
@@ -94,7 +102,12 @@
94102

95103
// add new flake?
96104
while ( flakesThisFrame-- ) {
97-
activeFlakes.push( new Snowflake(canvas.width) );
105+
if (snowflakePool.length) {
106+
activeFlakes.push( snowflakePool.pop().reset(canvas.width) );
107+
}
108+
else {
109+
activeFlakes.push( new Snowflake(canvas.width) );
110+
}
98111
}
99112

100113
var i = activeFlakes.length;
@@ -107,7 +120,7 @@
107120

108121
// splice flake if it's now out of rendering zone
109122
if (flake.y >= canvas.height || flake.y >= settlePoint[Math.floor(flake.x)]) {
110-
activeFlakes.splice(i, 1);
123+
snowflakePool.push.apply(snowflakePool, activeFlakes.splice(i, 1));
111124
// this flake effects our settle points
112125
if (flake.alpha > 0.8) {
113126
updateSettlePoints(flake);

0 commit comments

Comments
 (0)