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?
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With