Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web

HTML5 Canvas - Aqua Gauge

4.97/5 (26 votes)
23 Dec 2011CPOL3 min read 138.5K   6.2K  
Gauge control using HTML5 Canvas

Introduction

We all know HTML5 is picking up fast and it has already almost swallowed Silverlight and Flash. So, I started to learn HTML5 and to find out what was inside that makes it interesting. Having read it, now, I find HTML5 is fun, easy to learn and also feel it is the future of client applications. I started to learn by developing a UI control. As an example, I chose to write a gauge control which I developed few years agon in .NET 2.0 (Aqua Gauge).

Through this application, I have tried to explain some of the HTML5 canvas APIs and a full implementation of Gauge control.

Sample Image

How to Get Started?

All we need is a basic knowledge on HTML, JavaScript, CSS and a text editor tool and, of course, a HTML5 compatible browser. HTML5 has many new features for creating rich internet applications. Here, I’ll be concentrating on "canvas" element. To get started, open a text editor, enter the following HTML code and save it as "index.html".

HTML
<!DOCTYPE html>
<html>
<head><title>My first HTML5 App</title></head>
<body>
	<canvas width="300" height="200" style="border: 1px solid red;">
		Your browse doesn't support canvas :-(
	</canvas>
</body>
</html>

Open the index.html file in browser. If you see a red rectangle, then your browser supports HTML5 canvas. Otherwise, you need to upgrade your browser to continue.

Drawing on the Canvas

Now let’s add a few lines of JavaScript code to index.html to draw a rectangle on canvas.

HTML
<!DOCTYPE html>
<html>
<head><title>My first HTML5 App</title>
<script language="javascript">
	function drawSomething() {
		var canvas = document.getElementById('drawingBoard');
		var context = canvas.getContext('2d');
		context.fillStyle = "blue";
		context.fillRect(10, 10, 200, 100);
	}
</script>
</head>
<body onload="drawSomething()">
	<canvas id="drawingBoard" width="300" height="150">
		Your browse doesn't support canvas :-(
	</canvas>
</body>
</html>

Draw a Rectangle with Gradient

JavaScript
function drawSomething() {
    var canvas = document.getElementById('drawingBoard');
    var context = canvas.getContext('2d');

    var gradientBrush = context.createLinearGradient(0, 0, 0, canvas.width);
    gradientBrush.addColorStop(0, 'lightblue');
    gradientBrush.addColorStop(1, 'blue');
    context.fillStyle = gradientBrush;
    context.fillRect(0, 0, canvas.width, canvas.height);
}

Gradient Rectange

Draw Text Inside the Rectangle

JavaScript
context.fillStyle = "White";
context.font = "bold 30pt Arial";
var text = "HTML5 Canvas";
var txtWidth = context.measureText(text).width;
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
context.fillText(text, centerX-txtWidth/2, centerY);
context.restore();

Gradient Rectange with text

Add Code to Rotate the Text

JavaScript
context.save();
context.fillStyle = "White";
context.font = "bold 30pt Arial";
var text = "HTML5 Canvas";
var txtWidth = context.measureText(text).width;
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
context.translate(centerX, centerY);
context.rotate(-20 * Math.PI / 180);
context.fillText(text, -txtWidth/2, 0);
context.restore();

Gradient Rectange with rotated text

Draw a Translucent Circle using arc()

HTML
context.save();
//Text drawing code should go here. Below restore() will reset translate() 
//and rotate() operations.
context.restore();

context.fillStyle = "rgba(255, 255, 0 , 0.5)";
context.beginPath();
var x = canvas.width * 0.75;	
var y = canvas.height * 0.50;
var radius = 60;
var startAngle = 0;
var endAngle = 360 * Math.PI / 180;
context.arc(x, y, radius, startAngle, endAngle, true);
context.closePath();
context.fill(); 

Gradient Rectange with rotated text and translucent circle

Aqua Gauge Code

Now we know how to use the canvas element! The complete API specification for canvas is available here. The source code archive contains the following files:

  • Index.html – HTML file to host the canvas element
  • js\AquaGauge.js – contains the gauge implementation
  • js\Helper.js – contains utility methods to update gauge object properties with values from html controls
  • css\Styles.css – style sheet to layout the page. It uses few CSS3 constructs.
  • All other files in the archive are jQuery related files to enable slider controls.

You are now ready to explore the aqua gauge source code. Following are the properties of aqua gauge object.

Property NameTypeDescription
backgroundColorColorOverall canvas background color
dialColorColorCircular dial area background color
dialGradientColorColorCircular dial area inner background color for gradient
dialTitleStringDial title text. This will be placed at top
dialTitleTextFontFontDial title text font style
dialTitleTextColorColorDial title text foreground color
dialSubTitleStringDial sub title text. This will be placed at bottom
dialSubTitleTextFontFontDial sub title text font style
dialSubTitleTextColorCo<code>lorDial sub title text foreground color
dialValueTextFontFontCurrent value text font style
dialValueTextColorColorCurrent value text foreground color
showGlossinessBoolShows or hides glossiness
minValueIntMinimum value
maxValueIntMaximum value
noOfDivisionsIntNo of graduations/divisions on the scale
noOfSubDivisionsIntNo of sub graduations/divisions on the scale
majorDivisionColorColorMajor scale graduation color
minorDivisionColorColorMinor scale graduation color
rimColorColorRim arc color
rimWidthIntRim arc line width/thickness
rangeSegmentsArrayDefines the color ranges on the rim. Should be list of {start: [int], end: [int], color: [color] }
rangeSegments[].startIntRange arc start value
rangeSegments[].endIntRange arc end value
rangeSegments[].colorColorRange arc color
dialScaleFontFontMajor scale text font style
dialScaleTextColorColorMajor scale text color
dialSubScaleFontFontMinor scale text font style
dialSubScaleTextColorColorMinor scale text color
dialScaleTextShadowColorColorScale text shadow color
showMinorScaleValueBoolShows or hides minor scale value text
pointerColorColorPointer color
pointerGradientColorColorPointer gradient color
shadowColorColorPointer shadow color
currentValuefloatCurrent value the pointer points to

Using the Code

Create an HTML page like how we did in the above sample, then add AquaGauge.js reference and initialize the control as shown below. Use aGauge.refresh(value) to update the gauge current value.

HTML
<!DOCTYPE html>
<html>
<head>
    <title>Aqua Gauge</title>
    <script src="AquaGauge.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
        function showGauge() {
            var aGauge = new AquaGauge('gauge');
            aGauge.props.minValue = 0;
            aGauge.props.maxValue = 100;
            aGauge.refresh(45);
        }
    </script>
</head>
<body onload="showGauge()">
    <canvas id="gauge" width="300" height="300">Browser not supported.</canvas>
</body>
</html>

Conclusion

I have just started learning HTML5 and its related components. I’m excited that I was able to write this within a day! However, the code contains no proper validation and it is not tested properly. Hope you liked the article.

History

  • 23rd December, 2011: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)