canvas animation
by winddweb
HTML
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
canvas {
border: 1px solid;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
function animate(x, y) {
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
// update
// clear
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle="#ff0000";
ctx.fillRect(x,y,50,50);
// draw stuff
var dir = {x:true,y:true} ;
if(x == 50) {
dir.x = !dir.x;
console.log(x);
}
if(y == 150) {
dir.y = !dir.y;
}
if(!!dir.x){
x += 1;
}
if(!dir.x){
x -= 1;
}
if(!!dir.y){
y += 1;
}
if(!dir.y){
y -= 1;
}
// request new frame
requestAnimFrame(function() {
animate(x,y);
});
}
animate(0,0);
</script>
</body>
</html>