Rotate an object's coordinate set

I have a bunch of objects (ActiveRecord) that have x and y coordinates relative to an HTML5 canvas element. I need to rotate them at different levels (in 90 degree increments), and then save them again for a one-time data migration.

These objects are all relative to the canvas element, so the coordinates start at (0,0), and I would like them to stay in this quadrant (bottom right), if possible. I assume that I need to make a rotation around (0,0), and then translate down and to the right.

Is there a way to write a block that will do this? Any help is appreciated.

Update : some changes made it more clear after some questions.

Thanks.

+3
source share
1 answer
  • To rotate the point P, the number of R degrees around the origin:
    P2.x = Px * cos (R) - Py * sin (R)
    P2.y = Px * sin (R) + Py * cos (R)
    [quote]

  • You probably want to rotate around an arbitrary point in the center of the quadrant where you store the objects. If your quadrant is 200x100 wide, you need to rotate around the point <100,50>.

    To rotate point P around a location C other than the origin, you want to first translate the location to the origin, then rotate around the origin, and then translate back to C. In other words,
    P2 = P - C
    P3 = rotate (P2)
    P4 = P3 + C

    http://phrogz.net/SVG/rotations.xhtml - , , - , , , .

x y Ruby, :

Point = Struct.new(:x,:y) do
  def self.to_proc
    lambda{ |x| self.new *x }
  end

  def rotate( degrees, origin=Point.new(0,0) )
    radians = degrees * Math::PI/180
    x2 = x-origin.x; y2 = y-origin.y
    cos = Math.cos(radians); sin = Math.sin(radians)
    self.class.new(
      x2*cos - y2*sin + origin.x, 
      x2*sin + y2*cos + origin.y 
    )
  end

  def inspect
    "<%.1f,%.1f>" % [x,y]
  end
end

points = [ [0,0], [1,2], [3,4], [5,6] ].map(&Point)
p points
#=> [<0.0,0.0>, <1.0,2.0>, <3.0,4.0>, <5.0,6.0>]

p points.map{ |p| p.rotate(90) }
#=> [<0.0,0.0>, <-2.0,1.0>, <-4.0,3.0>, <-6.0,5.0>]

p points.map{ |p| p.rotate(90,Point.new(3,4)) }
#=> [<7.0,1.0>, <5.0,2.0>, <3.0,4.0>, <1.0,6.0>]
+9

All Articles