I decided to try and learn more about HTML5 canvas and build a page with the background as falling snow. I’d like to be able to do this dynamically (I know how to make objects move on canvas and etc. and could do this manually). What I mean by this is that I’d like to simply change a variable that controls how many snowflakes there are on the page at one time and not have to copy and paste code. I’m not 100% sure if my syntax is right for some of the objects and loops, either.
I tried looking for a tutorial to walk me through this the first time and couldn’t find any on how to make snow. If anyone happens to know of one and would give a link that would be great. Here is my code so far.
<!DOCTYPE html>
<html>
<head>
<title>Obese</title>
<style type="text/css">
body
{
background-color:black;
}
</style>
</head>
<body>
<script type="text/javascript">
function vp(woh)
{
var viewportwidth;
var viewportheight;
if (typeof window.innerWidth != 'undefined')
{
viewportwidth = window.innerWidth,
viewportheight = window.innerHeight
}
else if (typeof document.documentElement != 'undefined'
&& typeof document.documentElement.clientWidth !=
'undefined' && document.documentElement.clientWidth != 0)
{
viewportwidth = document.documentElement.clientWidth,
viewportheight = document.documentElement.clientHeight
}
else
{
viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
viewportheight = document.getElementsByTagName('body')[0].clientHeight
}
if (woh == 'w')
{
return viewportwidth;
}
else if (woh == 'h')
{
return viewportheight;
}
else
{
return false;
}
}
function snowflake()
{
this.x = Math.random() * canvas.width;
this.y = 0;
var toberadius = Math.random() * 50;
this.radius = toberadius + 10;
this.color = "white";
var tobefallingSpeed = Math.random() * 100;
this.fallingSpeed = tobefallingSpeed + 30;
numberofSnowflakes++;
}
function update(m)
{
if (snowflakes < numberofSnowflakes)
{
for (i=0;i<numberofSnowflakes;i++)
{
sf[i] = new snowflake();
snowflakes = i;
}
}
for (c=0;c<snowflakes;c++)
{
sf[m].y += sf[m].fallingSpeed * m;
}
}
function render()
{
for (b=0;b<snowflakes;b++)
{
ctx.fillStyle = "#FFFFFF";
ctx.fillRect(sf[b].x,sf[b].y,sf[b].radius,sf[b].radius);
}
}
function main()
{
alert('asdf');
now = Date.now();
delta = now - then;
update(delta/1000);
render();
then = now;
}
then = Date.now();
var int = self.setInterval("main()",1);
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = vp('w');
canvas.height = vp('h');
document.body.appendChild(canvas);
var numberofSnowflakes = 50;
var snowflakes = 0;
var sf = new Object();
</script>
</body>
</html>
As I mentioned in the comments, I actually created my own snow plugin thats been used on a few websites, Blog post and Github. So needless to say Im a fan of this effect :).
The code below should get you started.
Working Version