Skip to content

Instantly share code, notes, and snippets.

@rtouze
Created March 28, 2012 03:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rtouze/2223248 to your computer and use it in GitHub Desktop.
Save rtouze/2223248 to your computer and use it in GitHub Desktop.
Moving rectangle
<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>
//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")
}
}
@rtouze
Copy link
Author

rtouze commented Mar 28, 2012

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment