【问题标题】:Javascript canvas object gets stuck after rotating with ctx.Rotate()使用 ctx.Rotate() 旋转后,Javascript 画布对象卡住
【发布时间】:2020-08-10 08:23:25
【问题描述】:

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

汽车不再向右移动。

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

    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.net/GautamGXTV/g8v31t4r/215/

【问题讨论】:

    标签: javascript html5-canvas createjs easeljs


    【解决方案1】:

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

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

    另外说明一下,为所有渲染使用一个画布上下文是个好主意,因为您目前似乎正在获得 3 个单独的上下文。如果您还有其他问题,请随时提问!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-23
      相关资源
      最近更新 更多