要使点P在原点周围旋转一定量的R度:
P2.x = Px*cos(R) - Py*sin(R)
P2.y = Px*sin(R)+ Py*cos(R)
[引文] ]
您可能希望围绕要保持对象的象限中心的任意点旋转.如果您的象限是200x100单位宽,则您需要围绕该点旋转<100,50>.
要围绕原点以外的位置C旋转点P,您需要先将位置转换为原点,然后围绕原点旋转,然后转换回C.换句话说,P2 = P - C P3 =旋转(P2)P4 = P3 + C.
您可以在http://phrogz.net/SVG/rotations.xhtml上看到这一点- 单击以设置旋转中心,或更改旋转量,并在转换为原点的点组上设置变换,旋转,然后再翻译.
把它们放在一起,并用Ruby中的任意点旋转一个点x和y属性,你可以使用这样的代码:
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>]
Run Code Online (Sandbox Code Playgroud)