css rotate not working after left and top value change

Viewed 62

I have one div. I am trying to apply rotate css on mousedown/mousemove event on div itself.

It works correctly when I rotate first time.

But when left and top values are changed, rotate in anti-clockwise direction is not working. How do I fix this?

var img = $('.pointer');

 var offset = img.offset();
var mouseDown = false;


img.mousedown(function (e) {
    mouseDown=true;
});

$(document).mousemove(mouse);
function mouse(evt) {
    if(mouseDown ==true){
   
    var center_x = (offset.left) /*+ (img.width() / 2)*/;
    var center_y = (offset.top) /*+ (img.height() / 2)*/;
    var mouse_x = evt.pageX;
    var mouse_y = evt.pageY;
    var radians = Math.atan2(mouse_x - center_x, mouse_y - center_y);
    var degree = (radians * (180 / Math.PI) * -1) + 90;
    img.css('-moz-transform', 'rotate(' + degree + 'deg)');
    img.css('-webkit-transform', 'rotate(' + degree + 'deg)');
    img.css('-o-transform', 'rotate(' + degree + 'deg)');
    img.css('-ms-transform', 'rotate(' + degree + 'deg)');
    img.css('transition', 'all 0.1s');
    }
}

$(document).mouseup(function (e) {
    mouseDown = false;
    // offset = img.offset();
})


$('.changeTopLeft').click(function() {
    $('.pointer').css({
    left: '200px',
    top: '300px'
  });
});
.pointer {
    height:5px;
    position:absolute;
    top:150px;
    width:200px;
    border:1px solid red;
    left:150px;
    transform-origin: left top;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="pointer"></div>

<button class="changeTopLeft">change Top Left</button>

Here is a fiddle.

0 Answers
Related