Background panning after keydown effect

Asked

Viewed 67 times

2

Something is wrong with the method I’m using to recreate the Jsfiddle effect http://jsfiddle.net/LeoTheTitan/9Ttk5/

I want the background to move 10 pixels towards the keydown, and to continue to loop as the key is pressed or held again. I know the code below does not observe the factor "key kept pressed" - someone can help me implement this part?

The effect shall operate on the x and y axis and shall also be possible diagonally.

Follows 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');
    }
});
  • Your example doesn’t even work here: the properties you’re using were idealized as part of CSS3 but were rejected later. You will have to change x and y individually.

  • I’m sorry if you don’t understand the last sentence, I meant change them together, not individually.

1 answer

3


I arrived at that result: http://jsfiddle.net/95GhY/3/

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.

While the speed is non-zero this loop will be running every 10ms updating the image position. For better performance use the requestAnimationFrame, but it is not supported in all browsers.

  • 2

    Excellent! Your code has enough elegance to handle the issue. No lags and no unwanted animation effects. Answered masterfully. Also, note that changing the values in the speed array allows us to create a background with automatic panning. He ended up killing two birds with one stone. Ab.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.