Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

167
Visualizações
JavaScript/CSS keyframe animation that adjusts according to screen size

So I've been making a small game (by small, I mean a red box moving around a screen) and I decided, for some reason, to add a feature that automatically sets a certain aspect ratio so it can work on all window shapes and sizes. Now, my keyframe animations are broken because the use pixel coordinates. Here is the CSS with just the left animation:

#stage{
    border: 1px solid black;
    margin: auto;
}

#player{
    background-color: red;
    position: relative;
}

@keyframes moveLeft{
    0%{transform: translateX(0px);}
    80%{transform: translateX(-60px);}
}

.animateLeft{animation: moveLeft 125ms ease-out;}

And the JavaScript (removed non-left movements):

var game = {};
game.fps = 50;
var player = document.getElementById('player');
var stage = document.getElementById('stage');
var playerX = 0, playerY = 0;
var stageWidth, stageHeight;
var borderAspectRatio = 16/9;
var a = 0;
var isPlayerMoving = 0, newPlayerX = 0, newPlayerY = 0;

function checkPlayerMovement(){
    if(player.classList == 'animateLeft'){
        isPlayerMoving = 1;
    }
    else{
        isPlayerMoving = 0;
    }
};

function playerHalt(){
    isPlayerMoving = 0;
    setNewPlayerPosition();
    player.classList.remove('animateLeft');
};

function playerLeft(){
    player.classList.add('animateLeft');
    setTimeout(playerHalt,100);
};

function setNewPlayerPosition(){
    if(isPlayerMoving == 0){
        playerX = newPlayerX;
        playerY = newPlayerY;
    }
    setPlayerPosition();
};

function setPlayerPosition(){
    var playerSideLength = stageHeight/15;
    player.style.width = `${playerSideLength}px`
    player.style.height = `${playerSideLength}px`
    player.style.left = `${playerX + (stageWidth - playerSideLength) / 2}px`;
    player.style.bottom = `${playerY - (stageHeight - playerSideLength) / 2}px`;
};

document.addEventListener('keydown', function(event) {
    if(event.keyCode == 65) {a=1;}
});

document.addEventListener('keyup', function(event) {
    if(event.keyCode == 65) {a=0;}
});

function playerMotion(){
    checkPlayerMovement();
    if(a == 1){
        if(isPlayerMoving == 1){
            return;
        }
        else{
            newPlayerX -= 60; 
            playerLeft();
        }
    }
};

function scale(){
    var w = window.innerWidth;
    var h = window.innerHeight;
    if(w/h > borderAspectRatio){
        stageWidth = 0.96*h*borderAspectRatio;
        stageHeight = 0.96*h;
    }
    else{
        stageWidth = 0.96*w;
        stageHeight = 0.96*w/borderAspectRatio;
    }
    stage.style.width = `${stageWidth}px`;
    stage.style.height = `${stageHeight}px`;
};

game.run = function() {
    scale();
    setPlayerPosition();
    playerMotion();
};

game._intervalId = setInterval(game.run, 1000 / game.fps);

How can I change it to use some percentage (or something idk) of the screen instead of pixels?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Check out the Realtive length units on MDN (here)

especially the part about vh and vw, they're 1% of the viewport's height and 1% of the viewport's width respectively.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda