Click here to Skip to main content
12,511,383 members (134,879 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

70.7K views
4.9K downloads
63 bookmarked
Posted

HTML5 Canvas - Aqua Gauge

, 23 Dec 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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".

<!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.

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

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

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

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()

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
dialSubTitleTextColorColorDial 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.

<!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)

Share

About the Author

Ambalavanar Thirugnanam
Architect BNY Mellon
India India
Ambalavanar, working as a .NET Solutions Architect at BNY Mellon (iNautix), Chennai. Enjoys designing and developing UI & highly scalable apps.

You may also be interested in...

Comments and Discussions

 
AnswerGood Job.. Pin
Member 935325518-Nov-14 20:18
memberMember 935325518-Nov-14 20:18 
GeneralMy vote of 5 Pin
Tiancheng Hu28-Apr-14 19:42
professionalTiancheng Hu28-Apr-14 19:42 
GeneralMy vote of 5 Pin
onewarden25-Oct-13 3:14
memberonewarden25-Oct-13 3:14 
QuestionUsing Gauge as an Academic Diagonistic Tool Pin
StatsDr26-Jun-13 3:44
memberStatsDr26-Jun-13 3:44 
QuestionVery Good Pin
Syed Rizwan Shah14-May-13 1:22
professionalSyed Rizwan Shah14-May-13 1:22 
QuestionVery nice Pin
Member 993854824-Mar-13 12:28
memberMember 993854824-Mar-13 12:28 
QuestionChanging the Title and subtitle Pin
Bryan Wang1-Mar-13 5:41
memberBryan Wang1-Mar-13 5:41 
QuestionGreat Gauge Pin
Peter J Francis7-Jan-13 5:45
memberPeter J Francis7-Jan-13 5:45 
AnswerRe: Great Gauge Pin
Ambalavanar Thirugnanam15-Jan-13 15:04
memberAmbalavanar Thirugnanam15-Jan-13 15:04 
Thanks. It contains html and all related js and jquery resources.
-----------------------------
Go far with your knowledge...
Further with google...

GeneralMy vote of 3 Pin
Mcmish25-Oct-12 0:12
memberMcmish25-Oct-12 0:12 
GeneralExcellent work ! Pin
Sureshkumaar25-Sep-12 0:17
memberSureshkumaar25-Sep-12 0:17 
GeneralGreat Work Pin
Ibraheem Osama Mohamed29-Aug-12 1:35
memberIbraheem Osama Mohamed29-Aug-12 1:35 
GeneralMy vote of 5 Pin
manoj kumar choubey21-Aug-12 18:55
membermanoj kumar choubey21-Aug-12 18:55 
QuestionWoops here is my vote of 5!! Pin
Akshay Srinivasan215-Aug-12 11:16
memberAkshay Srinivasan215-Aug-12 11:16 
QuestionMy Vote of 5: Very nice gauge Pin
Akshay Srinivasan215-Aug-12 11:09
memberAkshay Srinivasan215-Aug-12 11:09 
GeneralMy vote of 4 Pin
Reza Ahmadi15-Jul-12 4:35
memberReza Ahmadi15-Jul-12 4:35 
GeneralMy vote of 5 Pin
Dave Lalande18-Apr-12 4:10
memberDave Lalande18-Apr-12 4:10 
QuestionData Source Pin
Dave Lalande18-Apr-12 3:56
memberDave Lalande18-Apr-12 3:56 
AnswerRe: Data Source Pin
Ambalavanar Thirugnanam18-Apr-12 9:37
memberAmbalavanar Thirugnanam18-Apr-12 9:37 
GeneralHTML5 Aqua guages. Pin
JustJimBean31-Mar-12 21:50
memberJustJimBean31-Mar-12 21:50 
Questionanimating the needle Pin
gfive7-Mar-12 1:58
membergfive7-Mar-12 1:58 
AnswerRe: animating the needle Pin
Ambalavanar Thirugnanam18-Apr-12 9:42
memberAmbalavanar Thirugnanam18-Apr-12 9:42 
GeneralMy vote of 5 Pin
Sachin_coder10-Jan-12 23:19
memberSachin_coder10-Jan-12 23:19 
GeneralRe: My vote of 5 Pin
Ambalavanar Thirugnanam20-Jan-12 4:39
memberAmbalavanar Thirugnanam20-Jan-12 4:39 
QuestionVote for 5 Pin
jslr0728-Dec-11 2:23
memberjslr0728-Dec-11 2:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160929.1 | Last Updated 23 Dec 2011
Article Copyright 2011 by Ambalavanar Thirugnanam
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid