Open In App
Related Articles

HTML5 Game Development | Infinitely Scrolling Background

Improve Article
Save Article
Like Article

Game Design and Development is an emerging industry. Although making AAA titles will require advanced knowledge of game engines, DirectX, OpenGL, etc. small HTML5 video game projects is a good place to start.

HTML5 canvas and javascript can be used to make small games while learning the fundamentals of game development like Collision-Detection, Object Pools, etc.

Infinitely Scrolling Background

An infinitely scrolling background is an important tool that is essential when making endless arcade games like flappy bird or in a normal platformer where you do not have the time or resources to hand-craft the entire level.

The idea is to draw the same image twice consecutively and replace the second image with the first when it occupies the entire screen effectively restarting the process.

Drawing an Image

The image should be such that the intermediate frames with parts of the 2 images are proper backgrounds and the separating line should not be visible. The same logic can be applied to create an infinite side scrolling background.
Here we will use this space background image as an example:


It was made using MS Paint. Any other software like Photoshop or Gimp can be used.

Writing the Code


<!DOCTYPE html>
    <title>Infinitely Scrolling Background</title>
<body style="background-color: black;">
   <canvas id="canvas1" style="border: 1px solid black;"></canvas>
<script src="main_javascript.js"></script>


// inside main_javascript.js
var can = document.getElementById('canvas1');
// The 2D Context for the HTML canvas element. It
// provides objects, methods, and properties to draw and
// manipulate graphics on a canvas drawing surface.
var ctx = can.getContext('2d');
// canvas width and height
can.width = 600;
can.height = 600;
// create an image element
var img = new Image();
// specify the image source relative to the html or js file
// when the image is in the same directory as the file
// only the file name is required:
img.src = "spacebg.png";
// window.onload is an event that occurs when all the assets
// have been successfully loaded( in this case only the spacebg.png)
window.onload = function() {
    // the initial image height
    var imgHeight = 0;
    // the scroll speed
    // an important thing to ensure here is that can.height
    // is divisible by scrollSpeed
    var scrollSpeed = 10;
    // this is the primary animation loop that is called 60 times
    // per second
    function loop()
        // draw image 1
        ctx.drawImage(img, 0, imgHeight);
        // draw image 2
        ctx.drawImage(img, 0, imgHeight - can.height);
        // update image height
        imgHeight += scrollSpeed;
        //resetting the images when the first image entirely exits the screen
        if (imgHeight == can.height)
            imgHeight = 0;
        // this function creates a 60fps animation by scheduling a
        // loop function call before the
        // next redraw every time it is called
    // this initiates the animation by calling the loop function
    // for the first time

Methods and Events

  1. getContext(‘2d’) : The HTML5 canvas tag is used to draw graphics via scripting (usually JavaScript).
    However, the canvas element has no drawing abilities of its own (it is only a container for graphics) – you must use a script to actually draw the graphics.
    The getContext() method returns an object that provides methods and properties for drawing on the canvas.

    var ctx = document.getElementbyId("canvasid").getContext('2d');


    The getContext(“2d”) object can be used to draw text, lines, boxes, circles, and more – on the canvas.

  2. window.onload : The onload event occurs when an object has been loaded. It is commonly used in javascript to trigger a function once an asset has been loaded.

    object.onload = function() { /*myScript*/ };


    window.onload specifically occurs on the successful load of all assets hence most of the javascript animation and rendering code for games are often written completely inside a function triggered by window.onload to avoid problems such as the drawImage() function being called before the image has been loaded.
    (try using a heavier image and calling the drawImage() function outside window.onload=function(){..} )

    It can also be used to check the visitor’s browser type and browser version, and load the proper version of the web page based on the information.

  3. window.requestAnimationFrame() : The window.requestAnimationFrame() method tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint. The method takes a callback as an argument to be invoked before the repaint.
    You should call this method whenever you’re ready to update your animation onscreen. This will request that your animation function be called before the browser performs the next repaint. The number of callbacks is usually 60 times per second, but will generally match the display refresh rate in most web browsers as per W3C recommendation.



    The callback_funtion is passed a single argument, a DOMHighResTimeStamp, which indicates the current time when callbacks queued by requestAnimationFrame() begin to fire.

Note: Your callback routine must itself call requestAnimationFrame() if you want to animate another frame at the next repaint.

Final Animation
The final canvas animation should look like this when the html file is opened :

Last Updated : 31 May, 2022
Like Article
Save Article
Similar Reads
Related Tutorials