Created
May 1, 2010 04:14
-
-
Save eee-c/386050 to your computer and use it in GitHub Desktop.
Canvas Tag Demo
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> | |
<style type="text/css"> | |
#canvas { | |
border: 1px solid black; | |
} | |
</style> | |
<script type="application/javascript"> | |
// key codes / directions | |
var left = 37, | |
up = 38, | |
right = 39, | |
down = 40; | |
var direction = null; | |
document.onkeydown = function(ev) { | |
switch(ev.keyCode) { | |
case left: | |
case up: | |
case right: | |
case down: | |
direction = ev.keyCode; | |
break; | |
default: | |
direction = null; | |
break; | |
} | |
if (direction) return false; | |
} | |
document.onkeyup = function(ev) { | |
direction = null; | |
} | |
function draw(ctx, me) { | |
ctx.beginPath(); | |
// clear drawing area | |
ctx.clearRect(0,0,500,500); | |
ctx.fillStyle = '#ffffff'; | |
ctx.strokeStyle = '#000000'; | |
ctx.fillRect(0,0,500,500); | |
// draw me and fill me in | |
ctx.rect(me.x,me.y,5,5); | |
ctx.fillStyle = '#000000'; | |
ctx.fill(); | |
ctx.stroke(); | |
ctx.closePath(); | |
var x_diff = 0; | |
if (direction == left) x_diff = -1; | |
if (direction == right) x_diff = 1; | |
var y_diff = 0; | |
if (direction == down) y_diff = 1; | |
if (direction == up) y_diff = -1; | |
var me_next = { | |
x: (me.x+x_diff > 0 && me.x+x_diff < 500) ? me.x+(5*x_diff) : me.x, | |
y: (me.y+y_diff > 0 && me.y+y_diff < 500) ? me.y+(5*y_diff) : me.y | |
}; | |
setTimeout(function(){draw(ctx, me_next)}, 25); | |
} | |
function init() { | |
var canvas = document.getElementById("canvas"); | |
var ctx = canvas.getContext("2d"); | |
var me = {x:250, y:250}; | |
draw(ctx, me); | |
} | |
</script> | |
</head> | |
<body onload="init()"> | |
<canvas id="canvas" width="500" height="500"></canvas> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can be seen at http://japhr.blogspot.com/p/canvas-demo.html. Described in more detail at: http://japhr.blogspot.com/2010/04/moving-in-canvas.html