1

I want to rotate a div element using CSS3 "transform:rotate". I want to get the degree from mouse position, like tracking the mouse.

How can i achieve this?

Thanks!

2
  • Use JavaScript to track the mouse and update the style. Commented Jul 24, 2013 at 7:31
  • yes, but how do i convert mouse position to the rotate degree? Commented Jul 24, 2013 at 7:33

2 Answers 2

5

Check

http://jsfiddle.net/arunberti/fSgPf/1/

$(document).ready(function() { // the same as yours. function rotateOnMouse(e, pw) { var offset = pw.offset(); var center_x = (offset.left) + ($(pw).width() / 2); var center_y = (offset.top) + ($(pw).height() / 2); var mouse_x = e.pageX; var mouse_y = e.pageY; var radians = Math.atan2(mouse_x - center_x, mouse_y - center_y); var degree = (radians * (180 / Math.PI) * -1) + 100; // window.console.log("de="+degree+","+radians); $(pw).css('-moz-transform', 'rotate(' + degree + 'deg)'); $(pw).css('-webkit-transform', 'rotate(' + degree + 'deg)'); $(pw).css('-o-transform', 'rotate(' + degree + 'deg)'); $(pw).css('-ms-transform', 'rotate(' + degree + 'deg)'); } $('.drop div img').mousedown(function(e) { e.preventDefault(); // prevents the dragging of the image. $(document).bind('mousemove.rotateImg', function(e2) { rotateOnMouse(e2, $('.drop div img')); }); }); $(document).mouseup(function(e) { $(document).unbind('mousemove.rotateImg'); }); }); 
Sign up to request clarification or add additional context in comments.

3 Comments

what should i do to achieve the same affect, with one change, rotate on bottom left transform-origin?
also the prefixed .css are not needed jQuery does that out of the box.
0
  • Use JS to get the element offset and pointer x, y coordinates
  • Use CSS rotate: with atan2(y, x)

const el = document.querySelector("body"); addEventListener("pointermove", ({x, y}) => { el.style.setProperty("--x", x - el.offsetWidth / 2); el.style.setProperty("--y", y - el.offsetHeight / 2); });
* { margin: 0; box-sizing: border-box; } body { min-height: 100dvh; display: flex; align-items: center; justify-content: center; container-type: size; } .circle { border-radius: 50%; background: red; offset: 0; width: 3em; aspect-ratio: 1; rotate: atan2(var(--y), var(--x)); &::after { content: ""; position: absolute; width: 50%; height: 2px; top: 50%; right: 0; background: #000; } }
<div class="circle"></div>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.