Calculating the origin of a rotated HTML element

I am currently dealing with the question of how to find the starting point before rotating the element.

In my project, I have two divs that cannot be in the same container with each other, which leads to the problem I am facing.

I am trying to calculate the starting point of an element that has already been rotated, so I can correctly place another element on it, and then apply the same degrees of rotation. To make sure that I have the right coordinates for the job, I have a div that marks a small square every time a rotation occurs. The blue square is for the starting point and the red square is for the center point where the element rotates. I thought I had a formula in Javascript, but there seems to be something wrong. The farther I am from 0 degrees or 180 degrees, the farther my other element drifts from where it should be. Below is the formula I have now.

var angle = (integer passed in to the function. Example: 45)
var rotatedX = blueBox.getBoundingClientRect (). left;
var rotatedY = blueBox.getBoundingClientRect (). top;
var centerX = redBox.getBoundingClientRect (). left;
var centerY = redBox.getBoundingClientRect (). top;

var dx = rotatedX - centerX;
var dy = rotatedY - centerY;

var toRadians = (Math.PI / 180);
var dx2 = dx * Math.cos (toRadians * angle) - dy * Math.sin (toRadians * angle);
var dy2 = dx * Math.sin (toRadians * angle) + dy * Math.cos (toRadians * angle);

var initialX = dx2 + centerX;
var initialY = dy2 + centerY;

elementToRotate.style.top = initialX + "px";
elementToRotate.style.left = initialY + "px";

// This just applies the CSS transform: rotate (45deg) to the element
elementToRotate.rotateDegrees (angle);

I originally worked on the formula here: HTML5 Canvas: calculating x, y point on rotation

, . . , , .

http://jsfiddle.net/aSr7J/1/ JS . , - . 0 180 45 .

+4
2

- , Y. html- Y , , .

, :

var dy = rotatedY - centerY;

var dy = centerY - rotatedY;

var initialY = dy2 + centerY;

var initialY = centerY - dy2;

JSFiddle.

+4

, , , . , div . jsfiddle demo.

1: , jQuery, . . Note2: -webkit- , , , , . javascript .

:

function alignRedToBlue() {
    var blue = document.getElementById("blue"),
        blueStyle = window.getComputedStyle(blue, null),
        red = document.getElementById("red"),
        props = ["transform", "-moz-transform","-webkit-transform", "-ms-transform", "-o-transform"],
        index, prop;
    for (index in props) {
        prop = props[index];
        red.style[prop] = blueStyle.getPropertyValue(prop);
    }
    red.style.top = blue.offsetTop + (blue.offsetHeight - red.offsetHeight) / 2 + "px";
    red.style.left = blue.offsetLeft + (blue.offsetWidth - red.offsetWidth) / 2 + "px";
}
+1

Source: https://habr.com/ru/post/1529294/


All Articles