使用ctx.Rotate()旋转后,Javascript画布对象被卡住。

问题描述 投票:0回答:1

我想做一个汽车游戏,每当你按一个方向键时,汽车就会旋转。我已经创建了汽车,但每次我尝试用ctx.Rotate旋转它时,汽车在移动一个特定点后就会卡住。就好像整个画布都被汽车旋转了一样。

车子不会再向右移动了。

car is stuck

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

    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();
}

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

变量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
}
    }
    }

如果你需要,这里有整个代码的链接。https:/jsfiddle.netGautamGXTVg8v31t4r215。

javascript html5-canvas createjs easeljs
1个回答
2
投票

其实你说的没错,当汽车旋转时,整个画布确实会被旋转。快速解决这个问题的方法是在旋转前保存画布的状态,然后在绘制汽车后再加载。可以这样做。

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();

还有一点,最好使用一个画布上下文来进行渲染,因为你目前得到的是三个不同的上下文。如果你还有其他问题,欢迎提问!

© www.soinside.com 2019 - 2024. All rights reserved.