0

I am new to JavaScript and am trying to learn it pretty fast. I need help with the keyboard event keys. I am trying to move an image in JavaScript using WASD. I can get it to move up, down, left, and right, but I cannot figure out how to get it to move diagonally. Help is greatly appreciated.

"use strict";

var cvs;
var ctx;
var imagex=100;
var imagey=100;

function keydown_callback(ev){
    if(ev.keyCode === 68 )
        imagex += 5;
    if(ev.keyCode === 65 )
        imagex -= 5;
    if(ev.keyCode === 87 )
        imagey -= 5;
    if(ev.keyCode === 83 )
        imagey += 5;
    draw();
 }

function draw(){
    ctx.clearRect(0,0,600,600);
    var background = new Image();
    background.src="wallpaper.jpg";
    ctx.drawImage(background, 0, 0, 600, 600);
    var img = new Image();
    img.src="ninja.png";
    ctx.drawImage(img,imagex,imagey,128,256);
}

function main(){
    var tmp = document.getElementsByTagName("body");
    var body = tmp[0];
    body.addEventListener("keydown",keydown_callback);
    cvs = document.getElementById("foo");
    ctx = cvs.getContext("2d");
    draw();
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
CRS
  • 827
  • 2
  • 13
  • 20
  • 4
    sidenote: you should not recreate that image every time, just use a global variable. – 11684 Aug 26 '12 at 17:44
  • 2
    @11684, Got it and was suggesting to take a look at the answer for http://stackoverflow.com/questions/5203407/javascript-multiple-keys-pressed-at-once – Vikdor Aug 26 '12 at 17:45
  • 2
    Instead of `var tmp = document.getElementsByTagName("body");var body = tmp[0];` you can use `var body = document.getElementsByTagName("body")[0];`, but the best is `document.body` – Oriol Aug 26 '12 at 18:30
  • This question is "how to get the image to move diagonally". Why can't you just change both `imagex` and `imagey`? If you increase them both by 5, then the image will move down and to the right at a 45 degree angle. – jfriend00 Aug 26 '12 at 18:30
  • jfriend00 - I tried that and it didn't work when i try to push both keys – CRS Aug 26 '12 at 18:50
  • @CRS - per my answer below, you pick a new key for diagonal motion and when that key is pressed, you change both the x and y values. You don't listen for two keys at once. It's possible to do that, but a lot more difficult. – jfriend00 Aug 26 '12 at 19:20

2 Answers2

1

See http://jsfiddle.net/7xkD7/1/ (click first to the result cell)

"use strict";
var cvs,
    ctx,
    imagex=100,
    imagey=100,
    mov={'x+':0,'x-':0,'y+':0,'y-':0};
function get(thing,key){
    for(var i in window[thing]){
        if(window[thing][i].indexOf(key)!==-1){return i;}
    }
    return false;
}
function changeMov(key,val){
    switch(key){
        case 68:case 39:
            mov['x+']=val;break;
        case 65:case 37:
            mov['x-']=val;break;
        case 87:case 38:
            mov['y-']=val;break;
        case 83:case 40:
            mov['y+']=val;break;
        default:return false;
    }
}

function keydown_callback(ev){
    var key=ev.which||ev.keyCode;
    if(changeMov(key,1)===false){return;}
    draw();
    ev.preventDefault();
    return false;
}
function keyup_callback(ev){
    var key=ev.which||ev.keyCode;
     if(changeMov(key,0)===false){return;}
}
function draw(){
    imagex+=5*(mov['x+']-mov['x-']);
    imagey+=5*(mov['y+']-mov['y-']);
    ctx.clearRect(0,0,600,600);
    var background = new Image();
    background.src="http://images1.videolan.org/images/largeVLC.png";
    ctx.drawImage(background, 0, 0, 100, 100);
    var img = new Image();
    img.src="http://www.nikon.com/swf/img/thumbnail_ophthalmic_lenses.png";
    ctx.drawImage(img,imagex,imagey,128,256);
}

function main(){
    var body = document.body;
    body.addEventListener("keydown",keydown_callback);
    body.addEventListener("keyup",keyup_callback);
    cvs = document.getElementById("foo");
    ctx = cvs.getContext("2d");
    draw();
}
Oriol
  • 274,082
  • 63
  • 437
  • 513
1

To make it move diagonally, you just pick a keycode that you want to move diagonally and when that key is pressed you change both the x and y values. If you change the x and y values by the same amount, it will move in a 45 degree angle.

See this demonstration of your code that uses the numeric keypad to move the image and moves it up/left with the Home key, up/right with the PgUp key, etc:

http://jsfiddle.net/jfriend00/TmbN5/

var cvs;
var ctx;
var imagex=0;
var imagey=0;
var img;

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();
jfriend00
  • 683,504
  • 96
  • 985
  • 979