Suppose your canvas is 1000 by 1000 and you want to plot points that are 0 to 7 in the x and -200 to 100 in the y. Then you need to do two things:
1) Recenter so that the origin is at (0, 333.3) in pixel coordinates. You would do this with translate(0, 333.3)
.
2) Scale so that an x of 7 appears at pixel position 1000 and y of 100 appears at pixel position -333.3 (now the top of the window). You would do this with scale(1000 / 7, -333.3 / 100)
.
More generally, for canvas size (w
, h
) and axis ranges xmin
...xmax
and ymin
...ymax
, you would do:
ctx.translate(w * xmax / (xmax - xmin), h * ymax / (ymax - ymin));
ctx.scale(w / (xmax - xmin), -h / (ymax - ymin));