Click here to Skip to main content
15,880,725 members
Articles / Web Development
Article

HTML5 Canvas - Aqua Gauge

Rate me:
Please Sign up or sign in to vote.
4.97/5 (26 votes)
23 Dec 2011CPOL3 min read 134.2K   6.2K   67   33
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)


Written By
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.

Comments and Discussions

 
QuestionDisplay Target value Pin
davideclem5-Jan-22 4:50
davideclem5-Jan-22 4:50 
Questionaquagauge information please Pin
LionMF79-Apr-20 22:49
LionMF79-Apr-20 22:49 
SuggestionWas Not working for Image Background Pin
Indiaaditya26-Nov-16 3:17
Indiaaditya26-Nov-16 3:17 
AnswerGood Job.. Pin
Member 935325518-Nov-14 20:18
Member 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
onewarden25-Oct-13 3:14 
QuestionUsing Gauge as an Academic Diagonistic Tool Pin
StatsDr26-Jun-13 3:44
StatsDr26-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
Member 993854824-Mar-13 12:28 
QuestionChanging the Title and subtitle Pin
Bryan Wang1-Mar-13 5:41
Bryan Wang1-Mar-13 5:41 
QuestionGreat Gauge Pin
Peter J Francis7-Jan-13 5:45
Peter J Francis7-Jan-13 5:45 
AnswerRe: Great Gauge Pin
Ambalavanar Thirugnanam15-Jan-13 15:04
Ambalavanar Thirugnanam15-Jan-13 15:04 
GeneralMy vote of 3 Pin
Mcmish25-Oct-12 0:12
Mcmish25-Oct-12 0:12 
GeneralExcellent work ! Pin
Sureshkumaar25-Sep-12 0:17
Sureshkumaar25-Sep-12 0:17 
GeneralGreat Work Pin
Ibraheem Osama Mohamed29-Aug-12 1:35
Ibraheem Osama Mohamed29-Aug-12 1:35 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey21-Aug-12 18:55
professionalManoj Kumar Choubey21-Aug-12 18:55 
QuestionWoops here is my vote of 5!! Pin
Akshay Srinivasan215-Aug-12 11:16
Akshay Srinivasan215-Aug-12 11:16 
QuestionMy Vote of 5: Very nice gauge Pin
Akshay Srinivasan215-Aug-12 11:09
Akshay Srinivasan215-Aug-12 11:09 
GeneralMy vote of 4 Pin
Reza Ahmadi15-Jul-12 4:35
Reza Ahmadi15-Jul-12 4:35 
GeneralMy vote of 5 Pin
Dave Lalande18-Apr-12 4:10
Dave Lalande18-Apr-12 4:10 
QuestionData Source Pin
Dave Lalande18-Apr-12 3:56
Dave Lalande18-Apr-12 3:56 
AnswerRe: Data Source Pin
Ambalavanar Thirugnanam18-Apr-12 9:37
Ambalavanar Thirugnanam18-Apr-12 9:37 
GeneralHTML5 Aqua guages. Pin
JustJimBean31-Mar-12 21:50
JustJimBean31-Mar-12 21:50 
Questionanimating the needle Pin
gfive7-Mar-12 1:58
gfive7-Mar-12 1:58 
AnswerRe: animating the needle Pin
Ambalavanar Thirugnanam18-Apr-12 9:42
Ambalavanar Thirugnanam18-Apr-12 9:42 
Hi Martijn,

Certainly doable. You may use jquery animate() to animate the currentValue property with an easing function.

Thanks!
-----------------------------
Go far with your knowledge...
Further with google...

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.