Skip to content
August 13, 2012 / geeksretreat

A progress bar using HTML5’s canvas

The default slider in HTML is rather basic and as of writing this post is only supported in Chrome – who knows why! The slider below is how Chrome renders the slider to screen:

A basic HTML5 slider control

Very basic indeed! In this point I have used HTML5’s canvas implementation to draw the following:

HTML5 slider control using Canvas

I hope you agree, it is slightly more appealing than the default. The HTML mark-up used to achieve this is:
<!--<span class="hiddenSpellError" pre=""-->DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8" />
<span class="hiddenSpellError" pre="">HTML5</span> Progress Slider
		<script src='progress.js'></script>
			<link rel="stylesheet" type="text/<span class=" />css" href="progress.css" media="all" />
	</head>
	<body onload='init();'>
		<canvas id="progress" width="670" height="161"></canvas>
		<form id="drawForm">
			<input id="slider" type="range" min="0" max="100" onchange="drawImage();" onkeyup="drawImage();"  />
		</form>
	</body>
</html>
The HTML is straight forward. The items of interest are the canvas element and the ‘onload’ event for the body. For those who are not familiar with HTML let me explain how we draw the slider onto the canvas. When any HTML page loads the browser will run the JavaScript code attached to the onload event of the body tag e.g.
<body onload='init();'>
In order to understand how the ‘init’ function works we need to understand how the browsers locates it. The browser will load any JavaScript code included in a script tag prior to displaying the page to the user e.g.
<script src="progress.js"></script>
Therefore, the content of the script “progress.js” will be loaded, and thus, the function called ‘init’ will be available. If you were to look inside the aforementioned script you will be able to see the code e.g.
function init() {

    canvas = document.getElementById('progress');

    // Create the image resource
    img = new Image();

    // Canvas supported?
    if (canvas.getContext) {

        ctx = canvas.getContext('2d');
        slider = document.getElementById('slider');

        // Setup the onload event
        img.onload = drawImage;

        // Load the image
        img.src = 'progress-tiles.jpg';

    } else {
        alert("Canvas not supported!");
    }
}
The ‘init’ function first obtains a handle to the canvas element we included in the HTML. It then verifies whether the browser supports the HTML5 canvas implementation. If so, a new image object is set and its source it set to the image ‘progress-tiles.jpg':

HTML slider base image and overlay

We then ask the browser to call the ‘drawImage’ function after the image has been loaded. This function contains the following:
function drawImage() {

    // Draw the base image - no progress
    drawBase(ctx);

    // Draw the progress segment level
    drawProgress(ctx);

}
The function contains two function calls. The first draws the base image (top half of the above image) onto the canvas.
function drawBase(ctx) {

    ctx.drawImage(img, 0, 0, iWIDTH, iHEIGHT, 0, 0, iWIDTH, iHEIGHT);

}
The second draws a portion of the complete image (bottom half of the above image) onto the canvas.
function drawProgress(ctx) {

    var x1 = 214, // X position where the progress segment starts
        x2 = 546, // X position where the progress segment ends
        s = slider.value,
        x3 = 0,
        x4 = 144,
        y1 = 63;

    // Calculated x position where the overlayed image should end

    x3 = (x1 + ((x2 - x1) / 100) * s);

    ctx.drawImage(img, 0, iHEIGHT, x3, iHEIGHT, 0, 0, x3, iHEIGHT);

    // Text to screen
    ctx.fillStyle = "grey";
    ctx.font = "14pt Arial";
    ctx.fillText(s + " %", x4, y1);
}
The above code is fairly simplistic, to aid the explanation here is how the constants (x1, x2) are derived.

The figures - not so arbitrary

And, to complement the above image: the x1 and x2 variables are used to calculates the relative x position along the progress segment for the current slider value (0-100%). This position is then used as the end point for the overlay image. Thus the portion of the overlay image deemed to be required is drawn over the base image. The x4 and y1 images relate to the location which the textual percentage is drawn.
That concludes one’s experiment with HTML5′s canvas. I hope this helps someone. All the code above may be taken and used for anything – credit not required. A working version of this project can be viewed here. The source code for this project can be obtained from my Git Hub repository here. Full credit for the original digital image goes to this site for source the PSD.
About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 162 other followers

%d bloggers like this: