Skip to content
Advertisement

How to represent any numbers in chart via canvas?

I want to create line chart via canvas, for data representation on vanilla JavaScript. For example canvas width 600px, height 400px. I have min and max possible numbers on Y axis and numbers between them. X axis represents date.

line chart example

This chart has maximum 1000 and minimum 0 (and numbers between them). I can use this numbers to draw dots in pixels on canvas. But if in future data maximum number will 75 and minumum 10, i should redraw dots on chart in pixels again in possible range.

The problem is how to translate any numbers from 0 to 1000, 10 to 75, 2k to 8k and so on to pixels to draw it on canvas to represent them, in 600px on 400px? or in 800px on 600px ?

For simple example. I have canvas 600x400px. I have range of numbers from 0 to 1000. 1000 equals 400px it’s placed on top of chart. 0 is 0 pixels placed on bottom of the chart. How much will 768 in pixels for example? What formula is here? How to translate numbers of any size to pixels?

Could explain how to achive that result? Maybe code samples or formulas

Advertisement

Answer

To find the Y axis in px the formula woulde be:
px to be find = (present value * max px)/max value
Ex:
X = (550*400)/1000 =>
X = 220,000/1,000 =>220 (that’s you px value to the Y axis)

The X axis is just a default distance that you set, at least that’s what I understood by your question.

Advertisement