HTML5 Game Development | Infinitely Scrolling Background

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 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:


 spacebg.png

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

Writing the Code

HTML:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


JavaScript:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 succesfuly 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;
  
        // reseting 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
        window.requestAnimationFrame(loop);
    }
  
    // this initiates the animation by calling the loop function
    // for the first time
    loop();
  
}

chevron_right


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.
    Syntax:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

    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.
    Syntax:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

    window.onload specifically occurs on the successfull 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.
    Syntax:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    window.requestAnimationFrame(callback_function);

    chevron_right

    
    

    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 :




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.