简体   繁体   English

无法在画布内旋转图像

[英]Can't rotate image inside canvas

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. 捕获左键<37 )和右键>39 )可以调用更新图像旋转因子的函数,在此示例中,此因子将转换为度。

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/ 请看这里的一个工作示例: http//jsfiddle.net/mathiasfcx/6ZsCz/3088/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM