JSFiddle - React, Tailwind, and code Playground
by jfriend00
HTML
<div id="descrip">Use the arrow keypad to move (up, down, left, right, Home, End, PgUp, PgDn).</div>
<button id="setFocus">Start</button>
<br><br>
<canvas id="foo"></canvas>
CSS
body {height: 1000px;}
JavaScript
var cvs;
var ctx;
var imagex=0;
var imagey=0;
var img;
// Warning - this keycode handling does not work in IE
function keydown_callback(ev){
var keymap = {
'38': [0,-5], // up
'40': [0,5], // down
'37': [-5,0], // left
'39': [5,0], // right
'36': [-5,-5], // up/left diagonal
'34': [5,5], // down/right diagonal
'33': [5,-5], // up/right diagonal
'35': [-5,5] // down/left diagonal
};
var move = keymap[ev.keyCode];
if (move) {
imagex += move[0];
imagey += move[1];
}
draw();
ev.preventDefault();
}
function draw(){
ctx.clearRect(0,0,1000,1000);
ctx.drawImage(img,imagex,imagey);
}
function main(){
img = new Image();
img.src="http://photos.smugmug.com/photos/344291068_HdnTo-Ti.jpg";
document.body.addEventListener("keydown",keydown_callback);
cvs = document.getElementById("foo");
ctx = cvs.getContext("2d");
draw();
// grab initial keyboard focus (in jsFiddle)
setTimeout(function() {
document.getElementById("setFocus").focus();
}, 1000);
}
main();