Dial Gauges using JavaScript

I needed some dial gauges for a weather station project. There are great looking gauges available out there, but they all seem to cost more than I'm willing to pay. I decided to try my hand at it. I'm not artsy, so they aren't the prettiest, but I will show you how to make your own, so you can apply your own artsy to them.

Browser Support

This is HTML5 stuff. All modern browsers have supported it for several years. If your browser does not support this, well, take from it what you will.

Last Things First

Before we get to making them, lets look at using them. The thing to the left is a gauge. It happens to be a thermometer, but that doesn't really matter. A gauge, to this code, is a div. The div has a background image. That image is 320 x 320 pixels, and looks like a gauge with no pointer. The canvas is inside the div, and the same size, so it lays completely over the image. It will contain the pointer. JavaScript paints the pointer on the canvas. The style contains a "float:left" to make it float on this page. It is not required for the gauge to operate.

<style>
	.gauge-temperature-f {
		width:320px;
		height:320px;
		background:url(/images/articles/gauges/gauge-temperature-f-black.png);
		float:left;
		margin:25px;
	}
</style>
<div class="gauge-temperature-f">
	<canvas id="temperature-f" height="320" width="320"></canvas>
</div>

To turn that into a gauge, we need to create a JavaScript object passing a few parameters:

<script>
var temperature = new gauge(
	"temperature-f",
	'/images/articles/gauges/needle.png',
	0,
	40,
	1.5);
</script>
  1. The ID of the canvas, in this case "temperature-f"
  2. The URL of the needle image
  3. The position on the dial of the value "0"
  4. The "number" at the very top of the dial. For this gauge, it is 40°F.
  5. The scale factor. How many digits on the dial per degree (of arc).

Since this gauge has 200° of temperature in 133° of dial, the factor is 200/133, or 1.5°F per ° of dial. Here's what the dial looks like while displaying a sweeping number.

The gauge to the left is just moving around, but if you told it "tempGauge.setPosition(72)" it would go to 72°F on the dial. If you view the source of this page you will see how simple the code is.

Go to Making Gauges

Copyright ©2000 - 2024 David Allmon All rights reserved. | Privacy Policy | Cookie Policy

Consent Preferences