简体   繁体   中英

Scaling a chart to a fixed screen height formula

This is a simple math problem, but for some reason I can't figure out the proper formula, been trying to work it out for the past hour with no success.

Let's say that we have a chart with a max point on the vertical axis chartMax and a min point on the vertical axis chartMin , and a max screen size height of 667, and we would like to fit this chart within this screen height regardless of its min and max values, it will always fit within the screen.

The chart has many points (hMin, hMax) each represented by a bar with a height h = Math.abs(hMax - hMin) , in order to fit all these points within the screen, we need to multiply the height of each point by a factor, what is the formula of this factor?

const chartMax = 4000;
const chartMin = 3500;

const screenMax = 667;

const factor = /* math magic */;

const points = [
  Math.abs(4000 - 3900) * factor,
  Math.abs(3800 - 3700) * factor,
  Math.abs(3600 - 3500) * factor,
];

If you only want to scale on the y-axis:

const height = chartMax - chartMin;
const scalar = windowHeight / height;   // scale factor

To transform the points from the chart to the screen:

function transformPoint(onChart) {
    return (onChart - chartMin) * scalar; // make lowest point drop to the bottom, and the others drop by the same amount
    // then scale it up from chart space to screen space
}

Here's an example: https://jsfiddle.net/bftbqqvv/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM