Background panning after keydown effect

2

Something is wrong with the method I'm using to re-create the effect of JSFiddle link

I want the background to move by 10 pixels in the direction of the keydown, and to keep moving in a loop as the key is pressed or held again. I know the code below does not look at the "key held down" factor - can anyone help me implement this part?

The effect should work on the x and y axis and should be possible also on the diagonal.

Follow the code:

HTML

<div id="pageBg"></div>

CSS

#pageBg {
background: url('http://placekitten.com/2000/2000') repeat 0 0 fixed;
height: 600px;
left: 0;
overflow: hidden;
position: fixed;
top: 0;
width: 100%;
}

JAVASCRIPT

var xPos = "background-position-x";
var yPos = "background-position-y";

window.addEventListener('keydown', function (e) {
    if (e.keyCode == 37) { //Left Arrow Key
            $('#pageBg').css(xPos, $('#pageBg').css(xPos) -10 + 'px');
    }
    if (e.keyCode == 38) { //Up Arrow Key
            $('#pageBg').css(yPos, $('#pageBg').css(yPos) -10 + 'px');
    }
    if (e.keyCode == 39) { //Right Arrow Key
            $('#pageBg').css(xPos, $('#pageBg').css(xPos) +10 + 'px');
    }
    if (e.keyCode == 40) { //Down Arrow Key
            $('#pageBg').css(yPos, $('#pageBg').css(yPos) +10 + 'px');
    }
});
    
asked by anonymous 06.03.2014 / 19:56

1 answer

3

I came up with this result: link

I created vectors of speed and position, if the keys are pressed the speed will change as configured by the key mapping and start a loop by setInterval .

As long as the speed is nonzero, this loop will be running every 10 ms updating the position of the image. For best performance use requestAnimationFrame , however it is not supported in all browsers.

    
06.03.2014 / 20:39