2

Y coordinate of rectangle after rotation on canvas. As shown in image the rectangle will be rotated on its center point axis. After rotation and canvas is restored I want to find the new X,Y coordinates like one shown in second image, before rotation points were 50,50 and after rotation they could be 62,40.

I found similar question so I took the images from there but that question is for some WPF and my requirement is JS. How to find coordinates of all corners of rectangle after rotation?

enter image description here

enter image description here

Community
  • 1
  • 1
Sandeep Kumar
  • 13,799
  • 21
  • 74
  • 110

1 Answers1

6

I made a simple JavaScript transformation class for this exact purpose.

Using it you can transform arbitrary points by a transform of your making.

When you transform the canvas, transform the Transform object in the same way and then call transformPoint(x, y) to get back the appropriate coordinates.

So in your case calling transformPoint(50, 50) would return about [62, 40], etc.

https://github.com/simonsarris/Canvas-tutorials/blob/master/transform.js

Here's an example: http://jsfiddle.net/b2fEX/

Simon Sarris
  • 62,212
  • 13
  • 141
  • 171
  • How would I use your JS transformation class to determine if a mouse click is on a rotated canvas where I draw a rectangle. I have the mouse coordinates on the unrotated canvas but I am having difficulty determining if it was clicked in the rotated rectangle. – Jack Stein Mar 14 '22 at 01:12
  • The code is not working in pure Java Script and requires Jquery. Is there any way to have the code configured to be in pure JS with no additional add on libraries? – Jack Stein Mar 15 '22 at 01:30
  • huh? This code does not use jQuery at all... – Simon Sarris Mar 15 '22 at 13:40
  • Sorry about this. You are correct, it was my mistake. – Jack Stein Mar 16 '22 at 01:16
  • Simon - I am trying to use your code to get the 4 vertices of the translated rectangle. My canvas will have multiple rotated rectangles and I need to determine on which one, if any, a user has mouse clicked, When I try to get your code to show me the 4 vertices of the rectangle, instead of just 1 it seem to be getting inaccurate results (negative numbers). What am I doing wrong in this code snippet in https://jsfiddle.net/jackmstein/e41y9nf6/6/ – Jack Stein Mar 16 '22 at 20:40