skip to Main Content

I would like to set a background image for this simple game I have created, but can’t figure out how to make the image be centred to the enter screen and cover all the pages height and width. I would also like the image to be a background, so the game can feature on-top of the image, the image should be an underlayer.

let character = document.getElementById('character');
let characterBottom = parseInt(window.getComputedStyle(character).getPropertyValue('bottom'));
let characterRight = parseInt(window.getComputedStyle(character).getPropertyValue('right'));
let characterWidth = parseInt(window.getComputedStyle(character).getPropertyValue('width'));
let ground = document.getElementById('ground');
let groundBottom = parseInt(window.getComputedStyle(ground).getPropertyValue('bottom'));
let groundHeight = parseInt(window.getComputedStyle(ground).getPropertyValue('height'));
let isJumping = false;
let upTime;
let downTime;
let displayScore = document.getElementById('score');
let score = 0;

function jump(){
    if(isJumping) return;
    upTime = setInterval(() => {
        if(characterBottom >= groundHeight + 250){
            clearInterval(upTime);
            downTime = setInterval(() => {
                if(characterBottom <= groundHeight + 10){
                    clearInterval(downTime);
                    isJumping = false;
                }
                characterBottom -= 10;
                character.style.bottom = characterBottom + 'px';
            }, 20);
        }
        characterBottom += 10;
        character.style.bottom = characterBottom + 'px';
        isJumping = true;
    }, 20);
}

function showScore(){
    score++;
    displayScore.innerText = score;
}

setInterval(showScore, 100);

function generateObstacle(){
    let obstacles = document.querySelector('.obstacles');
    let obstacle = document.createElement('div');
    obstacle.setAttribute('class', 'obstacle'); 
    obstacles.appendChild(obstacle);
    
    let randomTimeout = Math.floor(Math.random() * 1000) + 1000;
    let obstacleRight = -30;
    let obstacleBottom = 100;
    let obstacleWidth = 30;
    let obstacleHeight = Math.floor(Math.random() * 50) +50;
    obstacle.style.backgroundColor = `rgb(${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)})`;
    
    function moveObstacle(){
        obstacleRight += 5;
        obstacle.style.right = obstacleRight + 'px';
        obstacle.style.bottom = obstacleBottom + 'px';
        obstacle.style.width = obstacleWidth + 'px';
        obstacle.style.height = obstacleHeight + 'px';
        if(characterRight >= obstacleRight - characterWidth && characterRight <= obstacleRight + obstacleWidth && characterBottom <= obstacleBottom + obstacleHeight){
            alert('Game Over! Your score is: ' +score);
            clearInterval(obstacleInterval);
            clearTimeout(obstacleTimeout);
            location.reload();
        }
    }
    
    let obstacleInterval = setInterval(moveObstacle, 20);
    let obstacleTimeout = setTimeout(generateObstacle, randomTimeout);
}

generateObstacle();
    
function control(e){
    if (e.key == 'ArrowUp' || e.key == ' '){
        jump();
    }
}

document.addEventListener('keydown', control);
*{
    margin: 0;
    padding: 0;
}
body{
    width: 100%;
    height: 100vh;
    position: relative;
    overflow: hidden;
}
#ground{
    width: 100%;
    height: 100px;
    background-color: purple;
    position: absolute;
    bottom: 0;
}
#character{
    width: 50px;
    height: 50px;
    background-color: red;
    border-radius: 50%;
    position: absolute;
    bottom: 100px;
    right: calc(100% - 100px);
}
.obstacle{
    width: 30px;
    height: 100px;
    background-color: black;
    position: absolute;
    bottom: 100px;
    right: 0;
}
h2{
    font-family: sans-serif;
    margin-top: 10px;
    margin-left: 10px
<html lang="en"?
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, intial-scale=1.0">
    <title>Space Jump</title>
    <link rel="stylesheet" href="style.css">

</head>
<body>

<img src="bg.jpg" id="bg">

</body>
</html>
    <div id="ground"></div>
    <div id="character"></div>
    <div class="obstacles"></div>
    <h2>Score: <span id="score">0</h2>
    <script src="script.js"></script>
    
</body>
</html>

2

Answers


  1. Here is one way to solve this problem:

    Step 1: Create a container for the game

    <div class="game-container">
        ...
    </div>
    
    .game-container {
        width: 100vw;   /* Or whatever width you want */
        height: 100vh;  /* or whatever height you want */
        position: relative;
    }
    

    Step 2: Add the Background Image

    <div class="game-container">
        <img src="..." class="game-bg" />
    </div>
    
    .game-bg {
        /* Push the top border of the image 50% of the way down */
        top: 50%;
        /* Push the left border of the image 50% to the right */
        left: 50%;   
    }
    

    The CSS above will push the container so that the top left corner of the image is in the center of the screen. We want to center it, so we need to shift it, based on its width:

    .game-bg {
        /* Code from earlier here */
    
        transform: translate(-50%, -50%);
    }
    

    Since the parent container has position: relative, any element with position: absolute can be used to position elements relative to their container.

    You can also modify the z-index CSS property to add "depth" to your elements.

    Login or Signup to reply.
  2. Here is a simpler approach, unless you need the background to be an image tag.

    Add a div that resembles the sky, and set its height to (100% - the height of #ground). Adding this div will push the <h2> score div all the way to the bottom. To avoid that, position the <h2> using position: absolute and then add top: 0; to reposition it to the top left corner.

    <body>
        <div id="sky"></div>
        <div id="ground"></div>
        <div id="character"></div>
        <div class="obstacles"></div>
        <h2>Score: <span id="score">0</h2>
    </body>
    
    #sky {
        background-image: url("bg.jpg");
        height: calc(100% - 100px);
    }
    h2 {
        font-family: sans-serif;
        margin-top: 10px;
        margin-left: 10px;
        position: absolute;
        top: 0;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search