Coding HTML5/Javascript Linear Gauge without any libraray
A Pen by Hyyan Abo Fakher on CodePen.
Coding HTML5/Javascript Linear Gauge without any libraray
A Pen by Hyyan Abo Fakher on CodePen.
<canvas id="canvas" width="300" height="30"></canvas> |
(function(HyyanAF) { | |
'use strict'; | |
HyyanAF.LinearGauge = HyyanAF.LinearGauge || {}; | |
// constructor | |
HyyanAF.LinearGauge = function(canvas,inputLow,inputHigh){ | |
this.canvas = canvas; | |
this.inputLow = inputLow; | |
this.inputHigh = inputHigh; | |
this.canvasWidth = Number(canvas.getAttribute("Width")); | |
this.canvasHeight = Number(canvas.getAttribute("height")); | |
} | |
HyyanAF.LinearGauge.prototype = { | |
constructor: HyyanAF.LinearGauge, | |
translateRange: function( | |
Input , inputHigh , inputLow , outputHigh , OutputLow | |
){ | |
inputHigh = inputHigh ? inputHigh : this.inputHigh; | |
inputLow = inputLow ? inputLow : this.inputLow; | |
outputHigh = outputHigh ? outputHigh : 1; | |
OutputLow = OutputLow ? OutputLow : 0; | |
return ((Input - inputLow) / (inputHigh - inputLow)) * | |
(outputHigh - OutputLow) + OutputLow; | |
}, | |
draw: function(stops){ | |
// setup drawing context | |
var ctx = this.canvas.getContext("2d"); | |
// define the gradient | |
var gradient = ctx.createLinearGradient( | |
0, 0, this.canvasWidth, 0 | |
); | |
// draw stops from an array | |
// where every item is an array contains | |
// the position and the color of the gradient | |
for (var i = 0; i < stops.length; i++) { | |
gradient.addColorStop( | |
this.translateRange(stops[i][0]), | |
stops[i][1] | |
); | |
} | |
// defines the fill style on canvas | |
ctx.fillStyle = gradient; | |
// draw the a rect filled with created gradient | |
ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight); | |
return this; | |
}, | |
drawPointer: function(value,color,height){ | |
// setup drawing context | |
var ctx = canvas.getContext("2d"); | |
height = height ? height : 10; | |
ctx.strokeStyle = color ? color : '#000'; | |
ctx.lineWidth = 3; | |
// draw line indicate a value | |
ctx.beginPath(); | |
ctx.moveTo( | |
this.translateRange( | |
value, | |
this.inputHigh, | |
this.inputLow, | |
this.canvasWidth, | |
0 | |
), | |
0 | |
); | |
ctx.lineTo( | |
this.translateRange( | |
value, | |
this.inputHigh, | |
0, | |
this.canvasWidth, | |
0 | |
), | |
height | |
); | |
ctx.stroke(); | |
return this; | |
} | |
} | |
}(window.HyyanAF = window.HyyanAF || {})); | |
// Init | |
var canvas = document.getElementById('canvas'); | |
var stops = [ | |
[0, "#A770EF"], | |
[50, "#CF8BF3"], | |
[100, "#FDB99B"] | |
] | |
new HyyanAF.LinearGauge(canvas,0,100) | |
.draw(stops) | |
.drawPointer(1, '#fff' ,5) | |
.drawPointer(50, '#fff',5) | |
.drawPointer(90, '#fff') | |
.drawPointer(99, '#fff',5); |