0

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.

MightyMouse
  • 153
  • 1
  • 10
  • How is object defined? – Sascha Aug 11 '20 at 23:34
  • You need to apply some trigonometry here and calculate the projection. This is the formula you need: https://stackoverflow.com/questions/17410809/how-to-calculate-rotation-in-2d-in-javascript . I´ll give you a clue to start playing: `objClick=(e) => console.log("real coordinates are", rotate(OBJ_CENTER_X, OBJ_CENTER_Y, e.pageY - e.target.offsetTop, e.pageX - e.target.offsetLeft,-rotation))` – rupps Aug 12 '20 at 00:35
  • My apologize. object is basically $(this). – MightyMouse Aug 12 '20 at 02:07

0 Answers0