Created
February 4, 2012 17:14
-
-
Save lele85/1738991 to your computer and use it in GitHub Desktop.
Canvas 2D main loop test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE HTML> | |
<html> | |
<head> | |
<script> | |
window.onload = function(){ | |
function Ball(x, y, radius, speedX, speedY){ | |
this.LEFT_LIMIT = 0; | |
this.RIGHT_LIMIT = 800; | |
this.TOP_LIMIT = 0; | |
this.BOTTOM_LIMIT = 600; | |
this.__speedX = speedX; | |
this.__speedY = speedY; | |
this.__x = x; | |
this.__y = y; | |
this.__radius = radius; | |
this.draw = function(context){ | |
context.lineWidth = 5; | |
context.arc( | |
this.__x, | |
this.__y, | |
this.__radius, | |
0, | |
2*Math.PI, | |
false | |
); | |
this.__updateColor(context); | |
}; | |
this.update = function(){ | |
this.__x += this.__speedX; | |
this.__y += this.__speedY; | |
if (this.__x < this.LEFT_LIMIT){ | |
this.__x = this.LEFT_LIMIT; | |
this.__speedX *= -1; | |
} else if (this.__x > this.RIGHT_LIMIT){ | |
this.__x = this.RIGHT_LIMIT; | |
this.__speedX *= -1; | |
} else if (this.__y < this.TOP_LIMIT) { | |
this.__y = this.TOP_LIMIT; | |
this.__speedY *= -1; | |
} else if (this.__y > this.BOTTOM_LIMIT) { | |
this.__y = this.BOTTOM_LIMIT; | |
this.__speedY *= -1; | |
} | |
}; | |
this.__updateColor = function(context){ | |
context.strokeStyle = | |
'rgb(' + | |
Math.floor(255*this.__x/800) + | |
',' + | |
Math.floor(255*this.__y/600) + | |
',' + | |
50 + | |
');'; | |
}; | |
}; | |
var canvas = document.getElementById("myCanvas"); | |
var context = canvas.getContext("2d"); | |
var ball = new Ball(20,20,20,2,4.2); | |
var mainloop = function() { | |
context.beginPath() | |
ball.update(); | |
ball.draw(context); | |
context.stroke(); | |
}; | |
var animFrame = | |
window.requestAnimationFrame || | |
window.webkitRequestAnimationFrame || | |
window.mozRequestAnimationFrame || | |
window.oRequestAnimationFrame || | |
window.msRequestAnimationFrame || | |
null ; | |
var recursiveAnim = function() { | |
mainloop(); | |
animFrame(recursiveAnim); | |
} | |
animFrame(recursiveAnim); | |
}; | |
</script> | |
</head> | |
<body> | |
<canvas id="myCanvas" width="800" height="600" style="border: 1px dotted;"> | |
</canvas> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment