旋转后找到矩形的顶点 [英] Find vertices of rectangle after rotating it

查看:84
本文介绍了旋转后找到矩形的顶点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我承认我并不真正知道如何解释这个问题。但充分的解释应该有助于阐明一些光明。这是我所知道的。我在HTML5 Canvas上绘制了一个矩形。我知道所有4个角的点和宽度和高度。从这我可以计算中点。我想知道的是,如果我旋转矩形n degress,新的点将会是什么。所以例如我想从中心点旋转45度。四角的新顶点会是什么?希望完全解释我在找什么。代码示例,最好在JavaScript中,会很棒。提前致谢。

解决方案

这个函数计算你需要的东西。 'pivot'是旋转的起点(在你的情况下矩形的中心)。

 函数rotatePoint(pivot,point ,角度){
//顺时针旋转,以弧度表示的角度
var x = Math.round((Math.cos(angle)*(point [0] - pivot [0])) -
(Math.sin(angle)*(point [1] - pivot [1]))+
pivot [0]),
y = Math.round((Math.sin(angle)* (point [0] - pivot [0]))+
(Math.cos(angle)*(point [1] - pivot [1]))+
pivot [1]);
return [x,y];
};

将度数转换为randians:

 函数degToRad(deg){
return deg * Math.PI / 180;
}


So I admit I didn't really know how to phrase the question. But a full explanation should help shed some light. Here is what I know. I have a rectanlge drawn on an HTML5 Canvas. I know the points of all 4 corners and the width and height. From this I can calculate the mid-point. What I want to know is if I rotate the rectangle n degress, what the new points will be. So for example I want to rotate it 45deg from the center point. What will the new vertices of the four corners be? Hopefully that fully explains what I'm looking for. Code examples, preferably in JavaScript, would be great. Thanks in advance.

解决方案

This function calculates what you need. `pivot' is the origin of the rotation (the center of the rectangle in your case).

function rotatePoint(pivot, point, angle) {
  // Rotate clockwise, angle in radians
  var x = Math.round((Math.cos(angle) * (point[0] - pivot[0])) -
                     (Math.sin(angle) * (point[1] - pivot[1])) +
                     pivot[0]),
      y = Math.round((Math.sin(angle) * (point[0] - pivot[0])) +
                     (Math.cos(angle) * (point[1] - pivot[1])) +
                     pivot[1]);
  return [x, y];
};

To convert the degrees to randians:

function degToRad(deg) {
  return deg * Math.PI / 180;
}

这篇关于旋转后找到矩形的顶点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆