Created
March 10, 2014 21:51
-
-
Save ivanistheone/9475221 to your computer and use it in GitHub Desktop.
A super-simple demo of a block moving on canvas... for educational purposes
This file contains hidden or 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
<!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