In the spirit of the season, I wanted to make it snow on my website. So I began digging. Eventually I ended up with a script that moved an image element down the page in a snowflake-like manner. The problem with it was it was dependant on an img element for every flake - simply no poor programming when using an Object Oriented programming language.
So I decided I wanted to extend (in Java-speak; most of my programming background is in Java) the in-built Image object. The new object's src variable will lead to an image of the type of flake it is. (I want to be able to have more variance in images than a simple dot.) The new object will have a function that will allow it to move. A separate, unrelated function will control when each flakes move.
I did some more research and read about prototyping on JavaScript Kit and
here, but I still cant seem to get this to work. JS Lint says it's bug-free, but Firefox says "move()" is an invalid function. I am presuming the problem lies in my inability to fully grasp how to extend objects in JavaScript.
Code:
<html>
<head>
<script type="text/javascript">
Image.prototype.dFlake=dotFlake;
function dotFlake(xLocation,yLocation){
this.src = "simpleDotFlake.png";
this.x = xLocation;
this.y = yLocation;
}
dotFlake.prototype.move = fall;
function fall(){ // ^^ Belongs to dotFlake class.
this.style.position="absolute";
this.style.top = this.y;
this.style.left = this.x;
this.y= this.y + 1; // Falling is constant.
if (Math.random() > 0.5){ // Random direction, though.
this.x = this.x + 1;
} else{
this.x = this.x - 1;
}
}
function snow(flakes){ // Allows addition of different flakes later.
for (i in flakes){
i.move();
}
timer = setTimeout("snow()",1);
}
function startSnow(){
basicFlakes = new Array(new dotFlake(0,0));
snow(basicFlakes);
}
</script>
</head>
<body onload="startSnow()">
<h1>This is test text.</h1>
<img id="basicFlake" src="./simpleDotFlake.png" width="10" height="10" />
</body>
</html>
Any and all input is much appreciated.
Thank you!