Javascript 基于旋转的中心对象
我需要在画布上根据对象的旋转将其居中。我搞不懂数学 我有什么信息Javascript 基于旋转的中心对象,javascript,math,canvas,geometry,Javascript,Math,Canvas,Geometry,我需要在画布上根据对象的旋转将其居中。我搞不懂数学 我有什么信息 x、 和左上角的y坐标(参见图中的红色圆圈) 物体的宽度和高度 以度为单位的旋转值 到目前为止我试过什么 // center horizontally if (curretElement === null) return; curretElement.x((canvas.width() / 2) - ((curretElement.width() * curretElement.scaleX()) / 2)); canva
- 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
是对象应该居中的房间。更新:第一次尝试非常糟糕,所以我更新了代码。这实际上是可行的,并保持您的左角在容器的中心,只需填充角度输入
我想多提意见和要求,但我不能,这件事(赏金)很诱人
不依赖java脚本。也许你需要第二次尝试
角是容器和内容在前面。旋转,但它仍然存在。有帮助吗?评论它。
身体{
保证金:0;
}
#容器{
显示器:flex;
位置:绝对位置;
宽度:100%;
身高:100%;
}
#公羊{
显示器:flex;
背景色:黑色;
位置:绝对位置;
保证金:自动;
最高:50%;
右:50%;
}
#ram::之前{
内容:“;
位置:绝对位置;
高度:40px;
宽度:400px;
背景色:#000;
}
函数forf(){
var a=document.getElementById(“a”).value;
document.getElementById(“ram”).style.transform=“旋转(“+a+”度)”;
}
您可以通过以下方式计算坐标:
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 };
}
我假设左上角的x,y坐标是您想要计算的信息,而不是您拥有的信息?换句话说,对象的位置定位点是左上角,不管角度是多少?右,所以要做到这一点,您需要首先计算从对象中心到左上角的向量。这是
(-width*scale/2,-height*scale/2)
,您已经计算过了。将其添加到画布中心,就得到了angle=0的坐标,就像您已经做的一样。对于不同的角度,只需在将向量添加到画布中心之前旋转向量即可。你可以使用一个。这看起来像你在使用FabricJs。。。你能用konvajsthis发布一个完整但最小的projecti am代码片段吗。我的错误是我没有取物体的中间,但是左上角的x和y坐标(见图)非常感谢!不幸的是,这对我毫无帮助。不过还是要谢谢你的努力。