Eogcloud
Eogcloud

Reputation: 1365

Dynamic Scaling for canvas graphs

I'm working on a canvas JS application to facilitate graphing, it's a personal project.

An issue I'm having trouble with currently is scaling of variables to display visually.

for example, users enter a set of points, these can be any number. I cannot always 1:1 scale graph every-point. Imagine a canvas of 600x600 and values of (1000,1000) and (1,1). you would have to do some scaling/modification to decide where these points should be put on the graph.

How can one dynamically scale numbers like this and have them sit in reasonable places? Are there common approaches to solving this problem?

Upvotes: 0

Views: 74

Answers (1)

markE
markE

Reputation: 105015

Yes, you can "map" source values into a designated range.

This mapRange function allows you to scale/map your 1000x1000 values into your 600x600 canvas

// Given low,high values of the source(1000,1000)
// Given low,hight values of the mapped numbers (600,600)
// and given a value to map from the source to the destination range (value)
// map the source value into a designated range

function mapRange(value, sourceLow, sourceHigh, mappedLow, mappedHigh){

    return mappedLow + (mappedHigh - mappedLow) * 
           (value - sourceLow) / (sourceHigh - sourceLow);

}

Upvotes: 2

Related Questions