我一直在寻找该功能,到目前为止,我只是找不到我能理解的任何功能。我已经具有旋转功能以使其与位置相等,但是事实证明,使用0-360和所有参数时,它会变得有点困难。
我正在使用html canvas 2d上下文在笛卡尔坐标系上渲染对象。
我希望object1以简单的转弯率(R)面对positionX和positionY。
我不需要提供任何代码,因为您可能仍会自行编写代码。但是无论如何我都会在这里走:
let faceAt = function (thisObject,positionX,positionY) {
let desiredLocationX = positionX - thisObject.transform.x;
let desiredLocationY = positionY -thisObject.transform.y;
thisObject.transform.rotation = Math.degrees(Math.atan2(desiredLocationY, desiredLocationX));
};
(Math.degrees)函数将弧度转换为度。
答案 0 :(得分:1)
这个问题还不清楚。但是,我假设您实际上只是想在HTML5画布上围绕任意点旋转元素。
在画布上,一次只能绘制一个元素。您不能真正操纵单个元素-例如,您不能单独旋转一个元素。相反,您需要旋转整个画布。这将始终围绕画布的中心旋转,但是如果您移动画布原点,则会在画布的不同部分上绘制;从而使您可以绕一个点旋转。
查看以下示例。您可以单击画布上的任意位置,以使正方形围绕该点旋转。希望这是您所追求的:
let cv = document.getElementById("cv");
let ctx = cv.getContext("2d");
let angle = 0;
//Variables you can change:
let speed = 1; //Degrees to rotate per frame
let pointX = 250; //The x-coord to rotate around
let pointY = 250; //The y-coord to rotate around
ctx.fillStyle = "#000";
setInterval(()=>{ //This code runs every 40ms; so that the animation looks smooth
angle = (angle + speed) % 360; //Increment the angle. Bigger changes here mean that the element will rotate faster. If we go over 360deg, reset back to 0.
ctx.clearRect(0, 0, 400, 400); //Clear away the previous frame.
//Draw the point we are rotating around
ctx.beginPath();
ctx.arc(pointX,pointY,5,0,2*Math.PI);
ctx.fill();
ctx.closePath();
ctx.save(); //Save the state before we transform and rotate the canvas; so we can go back to the unrotated canvas for the next frame
ctx.translate(pointX, pointY); //Move the origin (0, 0) point of the canvas to the point to rotate around. The canvas always rotates around the origin; so this will allow us to rotate around that point
ctx.rotate(angle*Math.PI/180); //Rotate the canvas by the current angle. You can use your Math.degrees function to convert between rads / degs here.
ctx.fillStyle = "#f00"; //Draw in red. This is also restored when ctx.restore() is called; hence the point will always be black; and the square will always be red.
ctx.fillRect(0, 0, 50, 50); //Draw the item we want rotated. You can draw anything here; I just draw a square.
ctx.restore(); //Restore the canvas state
}, 40);
//Boring event handler stuff
//Move the point to where the user clicked
//Not too robust; relys on the body padding not changing
//Really just for the demo
cv.addEventListener("click", (event)=>{
pointX = event.clientX - 10;
pointY = event.clientY - 10;
});
#cv {
border:solid 1px #000; /*Just so we can see the bounds of the canvas*/
padding:0;
margin:0;
}
body {
padding:10px;
margin:0;
}
<canvas id="cv" width="400" height="400"></canvas><br>
Click on the canvas above to make the rectangle rotate around the point that was clicked.