what is the formula for getting the new X, Y
if I have the previus X, Y and the desired angle to rotate to.
the lines always start at 0, and go to the X, Y
function calcNewPoints(x, y, degree) {
return {x: something, y: something}
}
I tried but not find anything simple (only very hard maths)
from what I see if always start at 0 it means, the line is inside the circle and the x and y are the height and width of a triangle,
but still don't understand
console.clear();
const input = document.querySelector("input[type=range]");
const line = document.querySelector("#line");
const span = document.querySelector("span");
input.addEventListener("input", (e) => {
const result = `${Math.round(e.target.value) - 90}deg`;
line.style.rotate = result;
span.textContent = Math.round(e.target.value);
});
<script src="https://cdn.tailwindcss.com"></script>
<body >
<label >
<input type="range" min="0" max="360" value="0" />
<span></span>
</label>
<div id="line" ></div>
</body>
in this example, I want to find the blue dot x, y.
CodePudding user response:
Using Rotation-formulars you can calculate the position for the new x and y using the degree.
Sadly the english wiki page doesn't provide it in a simple way.
To rotate it counter-clockwise by α:
x1 = x * cos(α) - y * sin(α)
y1 = x * sin(α) y * cos(α)
And clockwise:
x1 = x * cos(α) y * sin(α)
y1 = -x * sin(α) y * cos(α)
Note: By multiplying the radiant with -1 you get the same result.
const input = document.querySelector("input[type=range]");
const line = document.querySelector("#line");
input.addEventListener("input", (e) => {
let angle = parseFloat(e.target.value, 10),
r = parseFloat(getComputedStyle(line).width, 10);
const result = `${angle}deg`;
line.style.rotate = result;
const
x = parseFloat((r * Math.cos(angle * Math.PI / 180)).toFixed(5), 10),
// y must be inverted as it rotates clockwise by default
y = -1 * parseFloat((r * Math.sin(angle * Math.PI / 180)).toFixed(5), 10),
// test value, rotated by 90° clockwise
rot = rotateByDegrees(x, y, 90);
output.value = `α:${angle % 360}°\nx:${x} y:${y}\nx1:${rot.x} y1:${rot.y}`;
});
function rotateByDegrees(x, y, degree, roundTo = 5, invert = false) {
const radiant = (invert ? 1 : -1) * degree * Math.PI / 180,
cos = Math.cos(radiant),
sin = Math.sin(radiant),
// round a bit to get rid of numbers like 4...-e15
round = (n) => parseFloat(n.toFixed(roundTo), 10);
return {
x: round(x * cos - y * sin),
y: round(x * sin y * cos),
}
}
input.dispatchEvent(new Event("input"));
<script src="https://cdn.tailwindcss.com"></script>
<body >
<label style="width: 100vw;">
<input type="range" min="0" max="360" value="270" /><br>
<output id="output" style="white-space: pre-wrap;"></output>
</label>
<div id="line" ></div>
</body>