jobo: flockenscript optimieren - fall als objektmethode mit setTimeout

Beitrag lesen

Hallo,

Wäre es schlau, eine Klasse zu bauen, mit eingebauter snow-Funktion?

Klassen kennt Javascript nicht, nur Objekte. Aber ein objektorientierter Ansatz würde dem Script sicherlich gut tun.

Oder die Sinusberechnung (horizentale Auslenkung) vorzuberechnen und in einem Array zu speichern?

  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html>  
	<head>  
	</head>  
<script type="text/javascript">  
[code lang=javascript]  
sinusTable = new Array;  
createSinusTable = function () {  
	for (k=-30;k<screen.height;k++) {  
	sinusTable[k] = 2*Math.sin(k/5);  
	}  
};  
  
Snowflake = function (xPosition) {  
	this.star=document.createTextNode("*");  
	/*put it in surrounding div, whiten it and append*/  
	this.div=document.createElement("div");  
	this.div.appendChild(this.star);  
	this.div.style.color="#fff";  
	DB.appendChild(this.div);  
	/* size and base-position and store for each snowflake*/  
	this.fontSize = Math.ceil(Math.random()*40);  
	this.div.style.fontSize=this.fontSize + "px";  
	this.div.style.position="absolute";  
	this.yPos=-this.fontSize;  
	this.xPos = xPosition;  
	this.div.style.left=10 + this.xPos + "px";  
	this.div.style.top= this.yPos+"px";  
};  
  
fall = function(j) {  
	if (mySnowflakes[j].yPos < myMarginBottom) {  
		mySnowflakes[j].yPos += myPixelsPerStep;  
		/* new postition, down and left/right for little sinus-swing*/  
		mySnowflakes[j].div.style.top = mySnowflakes[j].yPos + "px";  
		mySnowflakes[j].div.style.left = mySnowflakes[j].xPos + sinusTable[mySnowflakes[j].yPos] + "px";  
	}	else {  
		mySnowflakes[j].yPos=-mySnowflakes[j].fontSize;  
	}  
	/* to call in setTimeout-function, will be e.g. window[snow40](40)*/  
	setTimeout("fall("+j+")",myTimeout);  
};  
window.onload = function() {  
javascript:  
	createSinusTable();  
	DB=document.body;  
	DB.style.backgroundColor = "#000";  
	myStartMarginLeft = 40;  
	myDistanceBetweenFlakes = 10;  
	/* stop before bottom of window*/  
	myMarginBottom = screen.height - 150;  
	/* pixels to move for each step;*/  
	myPixelsPerStep = 1;  
	/* speed in msec*/  
	myTimeout = 10;  
	/* walk from left margin to end of screen*/  
	mySnowflakes = new Array;  
	for (i = myStartMarginLeft; i< screen.width; i += myDistanceBetweenFlakes) {  
		/*make a snowchristal*/  
		mySnowflakes[i] = new Snowflake(i);  
		functionCallNow = 'fall('+i+')';  
		/* start random*/  
		setTimeout(functionCallNow,Math.random()*50000);  
	}  
	void(0)  
	;  
}  

</script>
</head>
<body>
</body>
</html>
[/code]

Wie aber kriege ich die Funktion "fall()" als Methode des Objekts?

Gruß

jobo