Take the 2-minute tour ×

I have an image in the middle on my canvas, and I want to be able rotate it to face where my mouse is on the canvas.

I have the variables to my mouse position, and I have placed my image in a matrix so it currently rotates perfectly in the center with a given value, now I just need to connect the two.

var characterRotation = 0;

function characterController(){

    ctxMain.clearRect(0, 0, gameWidth, gameHeight);

    var charWidth = 65;
    var charHeight = 85;

    var srcX = 0;
    var srcY = 619;
    var drawX = gameWidth/2 - charWidth/2;
    var drawY = gameHeight/2 - charHeight/2;

    ctxMain.setTransform(1, 0, 0, 1, drawX, drawY);
    ctxMain.rotate(characterRotation * Math.PI/180);

    characterRotation = mouseX*2 / mouseY*2; // ?? this is what needs to roate my character

    ctxMain.drawImage(imgSprite, srcX, srcY, charWidth, charHeight, -charWidth/2, -charHeight/2, charWidth, charHeight);

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

From trig, the angle that you are looking for will be

sin( rotation ) = y / (x^2 + y^2)  # opposite/adjacent

but first you need to make sure your coordinates are centered, so subtract half the game width from mouseX and mouseY, then just use the above to get

rotation = Math.asin( y / (x*x + y*y)
share|improve this answer
add comment

Your Answer


