Misc scribbles

# Plotting a coordinate on the screen

#### 2017-02-16

I always end up having to remember the math for plotting a coordinate on the screen, for example an HTML5 canvas and end up stitching it together manually

If you step through the math it becomes very simple though

Say you have a coordinate range of 1000 to 2000 that you want to plot in a HTML5 canvas of size 100px

Let's do a quick example and then generalize. Let's say you want to plot the value 1500, and put it into screen coordinates, so you take that and subtract the minimum of the range

``````1500-1000
``````

Second, you know your point is going to be halfway in the range, and in general, to get this position, you divide now by the size of the interval you are plotting in, e.g. 2000-1000

``````(1500-1000)/(2000-1000) = 0.5
``````

We get 0.5 as expected. Then you multiply this proportion times the width of box you are rendering in, e.g. 100 pixels wide, and get that you put your pixel at position 50px

To summarize, the general formula for plotting a point x in a range (x1,x2) on a screen of width w is

``````w*(x -  x1) / (x2 - x1)
``````

Of course same thing applies for y

``````h*(y - y1) / (y2 - y1)
``````

This does not take into account small possible adjustments for closed vs open ranges, which could be important to avoid subpixel rendering on a canvas, but that can be a further exercise