问题描述
我需要根据对象的旋转将其在画布中居中。我无法弄清楚数学。
我有什么信息?
- 左上角的x和y坐标(请参见图像的红色圆圈)
- 物体的宽度和高度
- 以度为单位的旋转值
到目前为止我尝试了什么?
// center horizontally
if (curretElement === null) return;
curretElement.x((canvas.width() / 2) - ((curretElement.width() * curretElement.scaleX()) / 2));
canvas.draw();
// center vertically
curretElement.y((canvas.height() / 2) - ((curretElement.height() * curretElement.scaleY()) / 2));
canvas.draw();
当图像不旋转时,它将居中。
currentElement
是所选对象。
canvas
是对象应居中的房间。
解决方法
您可以通过以下方式计算坐标:
- 想象您的对象在画布上居中
- 计算相对于画布中心的左上角的坐标
- 围绕画布中心旋转对象,并计算相对于画布中心左上角的位置
- 将左上角的相对坐标转换回绝对坐标
以下是执行计算的函数:
function calculateXY(canvasWidth,canvasHeight,width,height,angle) {
//calculate where the top left corner of the object would be relative to center of the canvas
//if the object had no rotation and was centered
const x = -width / 2;
const y = -height / 2;
//rotate relative x and y coordinates by angle degrees
const sinA = Math.sin(angle * Math.PI / 180);
const cosA = Math.cos(angle * Math.PI / 180);
const xRotated = x * cosA - y * sinA;
const yRotated = x * sinA + y * cosA;
//translate relative coordinates back to absolute
const canvasCenterX = canvasWidth / 2;
const canvasCenterY = canvasHeight / 2;
const finalX = xRotated + canvasCenterX;
const finalY = yRotated + canvasCenterY;
return { x: finalX,y: finalY };
}
,
更新:第一次尝试真的很糟糕,所以我更新了代码。真正起作用,并使您的左角保持在容器中心,只需填充角度输入
我想发表评论并提出更多要求,但我不能,这个东西(赏金)很诱人
不很依赖于Java脚本。可能就是您需要第二次尝试。
角落是容器,之前是内容。旋转但它仍然在那里。有帮助吗?对其进行评论。
<!DOCTYPE html>
<html lang="en">
<body>
<style>
body{
margin:0;
}
#container{
display :flex;
position: absolute;
width:100%;
height:100%;
}
#ram{
display:flex;
background-color:black;
position:absolute;
margin:auto;
top:50%;
right:50%;
}
#ram::before{
content: "";
position:absolute;
height:40px;
width:400px;
background-color: #000;
}
</style>
<input type="number" id="a" onchange = "forf()">
<div id = "container">
<div id = "ram">
</div>
</div>
<script>
function forf(){
var a = document.getElementById("a").value;
document.getElementById("ram").style.transform = "rotate(" + a + "deg)";
}
</script>
</body>
</html>