Skip to content

Instantly share code, notes, and snippets.

@nielsdoorn
Created November 29, 2013 06:37
Show Gist options
  • Save nielsdoorn/7702288 to your computer and use it in GitHub Desktop.
Save nielsdoorn/7702288 to your computer and use it in GitHub Desktop.
Request animation frame JavaScript code
window.onload = init;
// variabelen
var canvas;
var x = 10;
var y = 10;
// init wordt eenmalig uitgevoerd om alles op te bouwen
function init() {
// canvas opvragen uit DOM
canvas = document.getElementById("animatie");
// pijltjestoetsen afhandeling regelen...
document.onkeydown = handleKeyboardInput;
initAnimation();
}
function initAnimation() {
// vraag aan de browser om maximaal 60 fps te animeren
window.looper = (function(callback){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback){
window.setTimeout(callback, 1000 / 60);
};
})();
(function animatieLoop(){
looper(animatieLoop);
tekenFrame();
})();
}
// het tekenen van het scherm
function tekenFrame() {
var ctx = canvas.getContext("2d");
// 2d context leeg maken, het canvas is 800px breed en 640px hoog
ctx.clearRect(0, 0, 800, 640);
// vierkantje tekenen
ctx.fillRect(x, y, 10, 10);
}
// pijltjes toetsen ingedrukt
function handleKeyboardInput(evt) {
evt = evt || window.event;
switch (evt.keyCode) { // iedere toets heeft een eigen code...
case 37: // pijltje links is 37
leftPressed();
break;
case 38: // pijltje omhoog is 38...
upPressed();
break;
case 39: // pijltje rechts
rightPressed();
break;
case 40: // pijltje omlaag
downPressed();
break;
}
}
// linker pijltje is ingedrukt
function leftPressed() {
x--;
}
// rechter pijltje is ingedrukt
function rightPressed() {
x++;
}
// pijltje omhoog is ingedrukt
function upPressed() {
y--;
}
// pijltje omlaag is ingedrukt
function downPressed() {
y++;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment