Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build a circular gauge html 5 canvas

I'm trying to build a circular gauge in canvas, and am having a really hard time with it. I essentially want this: enter image description here Just the white circle, red line, tic marks, the little ones, then a bigger one every 50, and a big tic mark with the number every 100, and the needle. I don't really care about any of the other writing on it or the silver border. Can anyone point me in the right direction? I'm pretty new to canvas but I'd like to not use any prebuilt libraries or anything.

Thanks!

like image 507
Bill Avatar asked Jan 20 '12 22:01

Bill


2 Answers

Here is a working example. I hesitated posting the entire code, because it's better when you can put it together yourself and comprehend what it's doing. It may be hard to edit this to do what you want to do, if you're not sure how it's put together. I've tried commenting what I could.

Even though it doesn't look like it, I started with Justin's example. I figured that was worth mentioning.

Click ON the gauge to increase pressure, acceleration, etc.

http://jsfiddle.net/JdLUw/

Output:

enter image description here

like image 86
WesleyJohnson Avatar answered Sep 21 '22 11:09

WesleyJohnson


This is a start: http://en.wikipedia.org/wiki/Polar_coordinate_system#Converting_between_polar_and_Cartesian_coordinates

I built something similar in PHP a decade ago or so. You could use an image as the base with the tick marks (something prettier than a couple of rendered ticks) and render the hand.

http://jsfiddle.net/2zhDp/

Change your code to this for the move() method...

var ctx = document.getElementById('pump-discharge').getContext('2d');
ctx.clearRect(0, 0, 150, 150); // clears rectangle after each move
var r = 40;
var rads = i*(Math.PI/180);
var x = r*Math.cos(rads) + 55;
var y = r*Math.sin(rads) + 55;

ctx.strokeStyle = "#D40000";
ctx.fillStyle = "#D40000";
ctx.lineWidth = 6;
ctx.beginPath();
ctx.moveTo(55, 55); 
ctx.lineTo(x, y); 
ctx.stroke();
like image 29
Justin Thomas Avatar answered Sep 19 '22 11:09

Justin Thomas