Trying to solve the problem of transformation and jumps during data transfer. https://jsfiddle.net/nevolgograd/v4ac3g7w/9/

The cube is spinning while the Alt + key is pressed. Movement occurs due to the transformation by turning on the pageX and pageY mouse, relative to the center of the screen. Everything works almost fine until I release one of the buttons and move the mouse to another point. The coordinates of the mouse change, the data is transferred to the transform: rotate and the cube makes this crazy reversal. How to avoid it? Simply put, how to set a new center of coordinates with each mouse click?

$("body").mousedown(function(event) { if(event.which == 1 && event.altKey) { moving = true; } if(moving) { $(document).mousemove(function(event){ var width = document.documentElement.clientWidth, halfWidth = document.documentElement.clientWidth/2, eventX = event.pageX - halfWidth, height = document.documentElement.clientHeight, halfHeight = document.documentElement.clientHeight/2, eventY = event.pageY - halfHeight; $('#cube').css({ 'transform':'rotateX(' + -eventY +'deg) rotateY(' + eventX + 'deg)' }) }); } }); $('body').mouseup(function(event){ if(event.which == 1 || event.altKey == false) { moving = false; $(document).off("mousemove"); } }); 

    1 answer 1

    Save the current position of the mouse when you click:

     $("body").mousedown(function(event) { if(event.which == 1 && event.altKey) { moving = true; $x= event.pageX; $y= event.pageY; 

    Then, when moving the mouse, add the difference to the current coordinates:

     $("body").mousemove(function(event){ if(moving) { eventX += event.pageX - $x; eventY += event.pageY - $y; $x=event.pageX; $y=event.pageY; 

    That's all the magic.

    And remove the alt from the end of rotation condition:

     $('body').mouseup(function(event){ if(event.which == 1) { moving = false; 

    Ideally, one should also add cancellation of selection with the mouse, otherwise rotation is buggy because of it:

     #cube { -webkit-user-select: none; /* Chrome all / Safari all */ -moz-user-select: none; /* Firefox all */ -ms-user-select: none; /* IE 10+ */ user-select: none; } 

    Result: https://jsfiddle.net/Ljcarqjd/1/

    • Just gorgeous. Thank you. - Igor Ivanov