EL- - 1 year ago 63

HTML Question

I am trying to create a graph calculator and making it display the graph correctly on a "canvas". When I load the HTML file and write x e.g it starts from the upper left corner and goes down to the lower right corner. So the problem is that it displays the graph upside down and it does not include negative values.

I know that the canvas starts from (0,0) in pixel value in the upper left corner and ends at (300,300) in the lower right corner. I want it to display something like the green canvas from this link: http://www.cse.chalmers.se/edu/course/TDA555/lab4.html

`points :: Expr -> Double -> (Int,Int) -> [Point]`

points exp scale (x, y) = [(x, realToPix (eval exp (pixToReal x))) | x<-[0..(fromIntegral canWidth)] ]

where

pixToReal :: Double -> Double --converts a pixel x-coordinate to a real x-coordinate

pixToReal x = x * 0.02

realToPix :: Double -> Double --converts a real y-coordinate to a pixel y-coordinate

realToPix y = y / 0.02

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

You're probably used to working with 2D coordinate systems where positive `y`

is up, but as you noted in HTML canvas positive `y`

goes down. To simulate the coordinate system you want, you need to flip all the `y`

-values over the line `y=0`

(aka the `x`

-axis).

Here are a few `y`

-values and their corresponding corrections you can use as tests. Note that I'm assuming `y`

has already been scaled properly; it looks like you've already got that part.

- 150 -> 0
- 0 -> 150
- -150 -> 300

The pattern is `y_new = -(y_old - 150)`

where 150 is `canvas_height/2`

. Therefore, after scaling you need to apply this formula to all your `y`

values.

To shift the `y`

-axis to the center you need to do the same sort of thing to derive the appropriate linear transformation.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**