Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A super-simple demo of a block moving on canvas... for educational purposes
<!DOCTYPE html>
<html>
<head>
<title>Canvas demo</title>
<meta name="author" content="Gabriel Poirier" />
<meta name="author" content="Ivan Savov" />
<meta name="description" content="A tutorial on the use of HTML canvas element." />
</head>
<body>
<!-- Contenu HTML de la page -->
<h1>Canvas demo</h1>
<canvas id="lecanvas"></canvas>
<!-- JavaScript -->
<script type='text/javascript'>
// settings
var CANVAS_WIDTH = 480;
var CANVAS_HEIGHT = 320;
var FPS = 20;
//
var canvas = document.getElementById('lecanvas');
canvas.width = CANVAS_WIDTH;
canvas.height = CANVAS_HEIGHT;
var ctx = canvas.getContext("2d");
// definition of the Player object
var Player = function(options){
// properties
this.x = 50;
this.y = 270;
this.width = 20;
this.height = 30;
this.color = "#333";
// methods
this.draw = function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.move_left = function() { this.x = this.x-5; };
this.move_right = function() { this.x = this.x+5; };
this.move_up = function() { this.y = this.y-5; };
this.move_down = function() { this.y = this.y+5; };
};
player = new Player();
function handle_keypress(e) {
console.log("key pressed");
e = e || window.event;
console.log( e.keyCode );
if (e.keyCode == '37') { // left arrow
player.move_left();
} else if (e.keyCode == '38') { // up arrow
player.move_up();
} else if (e.keyCode == '39') { // right arrow
player.move_right();
} else if (e.keyCode == '40') { // down arrow
player.move_down();
}
}
function draw_game() {
ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
player.draw();
}
// setup key binding
document.onkeydown = handle_keypress;
setInterval(function() {
draw_game();
}, 1000/FPS);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment