I have scenario where there are several items on a the context stack and I need to get an x, y coordinate relative to the canvas itself.
The situation is I am writing a 2D game in HTML5 and I want the “character” being controlled by the user to be able to aim towards the mouse. The character is nested in transformations. There is a camera object that transforms the canvas to follow the character and perform zooms/rotations, and of course the character itself is transformed downwards, and at times rotated away from it’s centre.
If I could get the position of my character relative to the canvas, I could do an atan2 to aim towards the mouse. Alternatively, if I could get the mouse coordinates relative to the centre of my character, then I could do the same.
Is there any way to do this other than to reverse all of my transform calculations?
Unfortunately I ended up manually reversing the transformations. The following code is what I put into the camera object:
the tmousex and tmousey are the transformed x and y positions of the mouse. This does not account for rotation – the reversal of the transformation will have to go into the character code (rotation of camera and character will just be added after the atan2 code).
Hope this helps anyone with the same problem.