Javascript canvas 对象在使用 ctx.Rotate() 旋转后卡住

Javascript canvas object gets stuck after rotating with ctx.Rotate()

我正在尝试制作一款汽车游戏,每次按下箭头键时汽车都会旋转。我已经创建了汽车,但每次我尝试用 ctx.Rotate 旋转它时,汽车在移动到特定点后就会卡住。就好像整个canvas都跟着车转了一样

汽车不会再向右移动了。

这是我旋转然后绘制汽车的代码:

    ctx.translate((canvas.width/2) - 50, (canvas.height/2) - 50);
    ctx.rotate(90*Math.PI/180);
    ctx.translate((-canvas.height.width/2) + 50, (-canvas.height/2) + 50);
    drawCircle(ctx, x, y);
    drawRect(ctx, x, y);
    drawWheels(ctx, x, y);

这是我的清车代码(用于刷新):

function clear(obj) {
    obj.save();
    obj.setTransform(1, 0, 0, 1, 0, 0);
    obj.clearRect(0, 0, canvas.width, canvas.height);
    obj.restore();
}

检查汽车是否到达canvas边缘的逻辑:

变量 x 和 y 是汽车的 x 和 y 坐标

var map = {}; // You could also use an array
    onkeydown = onkeyup = function(e) {
      e = e || event; // to deal with IE
      map[e.keyCode] = e.type == 'keydown';

    if (y < canvas.height && y > 0 && x < canvas.width && x > 0) {

      /* CODE FOR MOVING THE CAR GOES HERE */

      } else {

    if (y == canvas.height) {

    y = canvas.height -10
    }
        if (y == 0) {

    y = 10
}
else if (x >= canvas.width) {

x = canvas.width - 10

} 
else if (x == 0) {

x = 10
}
    }
    }

这里是完整代码的link,如果你需要的话: https://jsfiddle.net/GautamGXTV/g8v31t4r/215/

你确实是对的,整个 canvas 确实在汽车旋转时旋转。对此的快速解决方案是在旋转之前保存 canvas 的状态,然后在绘制汽车后加载它。它会是这样的:

ctx.save();
ctx.translate((canvas.width/2) - 50, (canvas.height/2) - 50);
ctx.rotate(90*Math.PI/180);
ctx.translate((-canvas.height.width/2) + 50, (-canvas.height/2) + 50);
drawCircle(ctx, x, y);
drawRect(ctx, x, y);
drawWheels(ctx, x, y);
ctx.restore();

另请注意,为所有渲染使用一个 canvas 上下文是个好主意,因为您目前似乎获得了 3 个独立的上下文。如果您还有其他问题,请随时提问!