Question

I have to plot a polyline in HTML5 canvas where y axis points are both positive and negative. such as y=[5,10,50,-150,80,-90]. The x-axis is spaced at 1. x=[1,2,3,4,5,6].

I am trying to use translate() and scale() to plot this, but so far not successful.

If someone could point how both positive and negative points be plotted in canvas it will be great.

Was it helpful?

Solution

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));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top