Skip to content

Instantly share code, notes, and snippets.

@eee-c
Created May 1, 2010 04:14
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 eee-c/386050 to your computer and use it in GitHub Desktop.
Save eee-c/386050 to your computer and use it in GitHub Desktop.
Canvas Tag Demo
<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>
@eee-c
Copy link
Author

eee-c commented May 1, 2010

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