I have a little JavaScript AJAX script that gets the speed on progress in kbps or whatever - let's say MB/s. And now I want add a gauge that shows the speed graphically.
I would have a image containing the gauge design and another with the pointer. The pointer by default points at the top - the lowest value would be -120deg and highest 120deg. But that wouldn't be nice if someone has a 1mb connection, so I need to add an exponential calculation.
Here are the values...
- 0-1MB: -120deg -> -90deg
- 1-5MB: -90deg -> -60deg
- 5-10MB: -60deg -> -30deg
- 10-20MB: -30deg -> 0deg
- 20-30MB: 0deg -> 30deg
- 30-50MB: 30deg -> 60deg
- 50-75MB: 60deg -> 90deg
- 75-100MB: 90deg -> 120deg
I totally don't know how to start with the calculation.
The animation is done by CSS
-webkit-transform:rotate(Xdeg)
and it would update on
xhr.onprogress
the calculation to get the speed is:
kb/s=((e.loaded/((new Date()-start)/1000))/1024).toFixed(2),
MB/S=(d/1024*8).toFixed(2)
When I have the MB/s I just want to set the gauge deg.
How can I achieve these values?
Here is a not-completely-working variant. I wrote it with while
but I think that it's not the proper way.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>gauge</title>
<style>
img{position:fixed;top:100px;left:100px;}
</style>
<script>
var b=[1,5,10,20,30,50,75,100,150],
deg=30;
get=function(a){
var l=b.length
while(l--){
if(b[l]<=a&&a<b[l+1]){
rotation=((l*deg)+(deg/(b[l+1]-b[l])*(a-b[l])));
pointer=document.getElementsByTagName('img')[1]
pointer.style['-webkit-transform']='rotate('+(rotation-120)+'deg)';
console.log(rotation)
}
}
}
</script>
</head>
<body>
<input onChange="get(this.value)">
<img src="gauge1.png"><img src="pointer.png">
</body>
</html>
It does not work with values under 5 and over 150.
EDIT here is the WORKING code for what i need
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>gauge</title>
<style>
img{position:fixed;top:100px;left:100px;}
.pointer{-webkit-transform:rotate(-120deg);}
input{width:100%;}
</style>
<script>
var pointer,
get=function(a){
var b=[0,1,5,10,20,30,50,75,100],l=b.length,c=30,x=-120;
if(a>=b[l-1]){
x=120;
}else{
while(l--){
if(b[l]<a&&a<=b[l+1]){
x=(c*l-120)+c*((a-b[l])/(b[l+1]-b[l]));
break;
}
}
}
pointer.style['-webkit-transform']='rotate('+x+'deg)';
}
window.onload=function(){
pointer=document.getElementsByClassName('pointer')[0];
}
</script>
</head>
<body>
<img src="gauge1.png"><img class="pointer" src="pointer.png">
<input type="range" min="0" max="100" value="0" onChange="get(this.value)" step="0.1">
</body>
</html>