How to calculate CSS rotate method degree using Javascript

179 Views Asked by At

Following is my speedometer. I want to calculate the degree of the pointer which will be used in CSS transform:rotate() property.

Speedometer Design

to keep the pointer at 300 score my degree is -85 i.e.transform:rotate(-85deg) and to keep it at 900 my degree is 85 i.e.transform:rotate(85deg).

So now I want to dynamically calculate the degree based on the score. If the score is below 300, I will use -85deg and if its above 900 then I will use 85deg. How can I calculate degree if the score is between 300 to 900 and degree should be between -85 to 85. I am not good at trigonometry.

I tried to calculate the using percentage but I think, I am doing that calculation wrong

1

There are 1 best solutions below

0
Lawrence Cherone On BEST ANSWER

Get the 0 to 100 percentage of the value in the range of 300 to 900, then use that percentage to get the value of where that percentage sits in the angle range, then simple check on min and max constraints:

function getRotation(value, options) {
  const result = options.range.min + (options.range.max - options.range.min) * (((value - options.value.min) * 100) / (options.value.max - options.value.min) / 100)
  
  if (result < options.range.min) return options.range.min
  if (result > options.range.max) return options.range.max
  return result
}

const options = {
  value: {
    min: 300,
    max: 900
  },
  range: {
    min: -85,
    max: 85
  }
}

console.log(getRotation(0, options))    // -85
console.log(getRotation(300, options))  // -85
console.log(getRotation(600, options))  // 0
console.log(getRotation(900, options))  // 85
console.log(getRotation(1000, options)) // 85