Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't rotate image inside canvas

Tags:

javascript

if (player1Ready) {
    ctx.save();  
    ctx.rotate(player1.rotation);  
    ctx.drawImage(player1Image, player1.x, player1.y,80,80);
    ctx.restore();  }

I'm trying rotate a single image inside a canvas based on how much a player has pressed left or right.

I can't get my head around how this works, can anyone help?

like image 571
user3378734 Avatar asked Nov 27 '25 22:11

user3378734


1 Answers

Capturing the left key < (37) and the right key> (39) you can call a function that update the image rotation factor, in the example this factor is converted to degrees.

document.onkeydown = function (e) {
    if(e.keyCode == 39){
        angleInDegrees+=5;
        drawRotated(angleInDegrees);
    }else if(e.keyCode == 37){
        angleInDegrees-=5;
        drawRotated(angleInDegrees);
    }
}

function drawRotated(degrees){
    ctx.clearRect(0,0,canvas.width,canvas.height);
    ctx.save();
    ctx.translate(canvas.width/2,canvas.height/2);
    ctx.rotate(degrees*Math.PI/180);
    ctx.drawImage(image,-image.width/2,-image.width/2);
    ctx.restore();
}

See one working example here: http://jsfiddle.net/mathiasfcx/6ZsCz/3088/

like image 185
Mathiasfc Avatar answered Nov 30 '25 13:11

Mathiasfc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!