Created
March 28, 2012 03:09
-
-
Save rtouze/2223248 to your computer and use it in GitHub Desktop.
Moving rectangle
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
<html> | |
<head> | |
<title>Test des canvas html5</title> | |
<script type="text/javascript" src="canevasTest.js"></script> | |
</head> | |
<body> | |
<div id="titre"></div> | |
<canvas id="caca" width="640" height="480">Normalement, canvas marche</canvas> | |
</body> | |
</html> |
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
//jouons avec canvas | |
window.onload = function(){ | |
direction = 1; | |
caca = null; | |
ctx = null; | |
init(); | |
main(); | |
} | |
function init() { | |
caca = document.getElementById("caca"); | |
window.addEventListener("keypress", function() { | |
direction *= -1; | |
i += 2*direction; | |
}); | |
} | |
function main() { | |
setTitle(); | |
if(caca != null) { | |
ctx = caca.getContext("2d"); | |
ctx.fillStyle="#FF0000"; | |
i = 10; | |
console.log("go"); | |
interv1 = setInterval(draw, 10); | |
} else { | |
console.log("Caca not found"); | |
} | |
} | |
function draw() { | |
if(i >= 10 && i <= caca.width - 150) { | |
ctx.clearRect(0,0, caca.width, caca.height); | |
ctx.fillRect(i, 50, 150, 75); | |
i += direction; | |
} | |
} | |
function setTitle() { | |
var titre = document.getElementById("titre"); | |
if(titre != null) { | |
titre.innerHTML = "Presse une touche pour changer de direction."; | |
} else { | |
console.log("titre not found") | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
La fonction setTitle était juste un test pour voir si le javascript était correctement interprété (j'ai toujours du mal à commencer).
Le secret pour animer un canvas est d'utiliser la commande setInterval, qui lance la fonction en 1er paramètre tout les X ms où X est le second paramètre. Il suffit ensuite de redessiner le contenu.