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();
}
6
  • 4
    sidenote: you should not recreate that image every time, just use a global variable. Commented Aug 26, 2012 at 17:44
  • 2
    @11684, Got it and was suggesting to take a look at the answer for stackoverflow.com/questions/5203407/… Commented Aug 26, 2012 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 Commented Aug 26, 2012 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. Commented Aug 26, 2012 at 18:30
  • jfriend00 - I tried that and it didn't work when i try to push both keys Commented Aug 26, 2012 at 18:50

2 Answers 2

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();
}
Sign up to request clarification or add additional context in comments.

Comments

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();

1 Comment

If you press the PgUp, PgDn Home or End keys in the jsFiddle, the image moves diagonally.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.