In JavaScript/jQuery, if we wanted to rotate an element around an origin point defined by the click point, you could do this:
var angle = 0;
$('#myElement').on('click', function(event) {
const ELEMENT_X = event.pageX - $(this).offset().left;
const ELEMENT_Y = event.pageY - $(this).offset().top;
angle +=10;
$(this).css('transform-origin', ELEMENT_X + 'px ' + ELEMENT_Y + 'px');
$(this).css('transform', 'rotate(' + angle + 'deg)');
});
So it works as planned on the first click because the element is not in a rotated state. After the first rotation, the ELEMENT_X AND ELEMENT_Y are not set correctly obviously, which causes the origin point to be incorrect. Is there a formula we can apply that would find the correct x and y values to set on a click point for the CSS transform-orign
property based on the current angle of the element?
I'm not too sure if this article is the same as mine: How we can calculate the correct x and y value for the rotated image?
This thing is driving me nuts. I made a JSFiddle:
https://jsfiddle.net/f251qL98/
The goal here is to make the element rotate around any point within the element that we click on. By default, the origin point is set at the center of the element. The first click works fine, but subsequent ones, the element rotates around the incorrect origin point.
But if we click on another part of the element, I'm not too sure where the origin would be located, especially if the object has been rotated. I'm sure it is some math triangle manipulation solution, but that is not my strong side. Anyhow, back to testing all try to test more possibilities.