JSFiddle - React, Tailwind, and code Playground
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
// definição de variáveis:
var elemento = $('#pageBg');
var velocidade = [0, 0];
var posicao = [0, 0];
var teclaMapping = {
'37': [1, 0],
'38': [0, 1],
'39': [-1, 0],
'40': [0, -1]
};
var intervalo;
// função que anima o fundo do elemento:
function loop () {
posicao[0] += velocidade[0]; posicao[1] += velocidade[1];
elemento.css('background-position', posicao[0] + 'px ' + posicao[1] + 'px');
}
// Quando apertar uma tecla:
$('html').on('keydown keyup', function (evt) {
var mapa = teclaMapping[evt.which],
delta = evt.type === 'keydown'? 1: -1;
// Só aperta a tecla se ela já estiver configurada
// e se o estado dela alterou:
if (mapa && mapa[2] !== evt.type) {
velocidade[0] += delta * mapa[0];
velocidade[1] += delta * mapa[1];
mapa[2] = evt.type;
}
// Caso a velocidade seja diferente de zero:
if (velocidade[0] || velocidade[1]) {
// Inicia o intervalo, caso ele tenha sido interrompido:
if (!intervalo) {
intervalo = setInterval(loop, 10);
}
} else {
// Parar o intervalo se estiver parado:
clearInterval(intervalo);
intervalo = null;
}
});