2

Experts,

I created an image(#hand) movement along with mouse cursor (when being inside a div). This part is working fine unless when there is a transform rotate to #handWrap div. The hand image position moves different on a rotated parent div. I know, we should do some sort of calculation before passing the e.pageX and e.pageY position directly to hand, but couldn't find a proper fix. Would appreciate if anyone could help.

HTML:

<div id="handWrap">
    <img id="hand" src="http://s30.postimg.org/s4f5oy9dd/hand.png"/>
</div>

CSS:

* { margin:0; padding:0; }
#handWrap {
    position:absolute;
    top:40px;
    left: 80px;
    width:200px;
    height:300px;
    overflow:hidden;
    border:1px solid red;
    /* try uncommenting below, hand position not being accurate */
    /* transform: rotate(-10deg); */
    cursor:pointer;
}
#hand{
    position: absolute;
    transform: rotate(10deg);
}

jQuery:

$("#handWrap").on("mousemove",function(e){
    // I played with sin/cos/half-width etc, but doesn't worked
    $('#hand').css({'left':e.pageX-130,'top':e.pageY-44});
});

JSfiddle demo here: In jsfiddle, try uncommenting the transform rotate in #handWrap, then run, we could see hand movement is not accurate with mouse cursor

http://jsfiddle.net/y4pfd7u2/4/

Thanks in advance!

Shiv
  • 1,211
  • 4
  • 14
  • 24

1 Answers1

3

Well, finally I figured it out. As per the answer to this question, you can find the coordinates of the point after rotation using the rotate function below. Here is the final working version of your problem (and also JSFiddle):

$("#handWrap").on("mousemove",function(e){
    // I played with sin/cos/half-width etc, but doesn't worked
    var point = rotate(e.pageX, e.pageY, 100, 150, 10);
    $('#hand').css({'left':point[0]-110,'top':point[1]-30});
});


function rotate(x, y, xm, ym, a) {
    var cos = Math.cos,
        sin = Math.sin,

        a = a * Math.PI / 180, // Convert to radians because that's what
                               // JavaScript likes

        // Subtract midpoints, so that midpoint is translated to origin
        // and add it in the end again
        xr = (x - xm) * cos(a) - (y - ym) * sin(a)   + xm,
        yr = (x - xm) * sin(a) + (y - ym) * cos(a)   + ym;

    return [xr, yr];
}
* { margin:0; padding:0; }
#handWrap {
 position:absolute;
 top:40px; left: 80px;
 width:200px; height:300px;
 overflow:hidden;
 border:1px solid red;
    /* try uncommenting below, hand position not being accurate */
 transform: rotate(-10deg);
    cursor:pointer;
}
#hand{
 position: absolute;
 transform: rotate(10deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="handWrap">
    <img id="hand" src="http://s30.postimg.org/s4f5oy9dd/hand.png"/>
</div>

If anything is not clear for you regarding the solution or the equations, please ask me.

Community
  • 1
  • 1
Karlen Kishmiryan
  • 7,322
  • 5
  • 35
  • 45