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

落爺英雄遲暮 提交于 2020-06-01 06:03:09

问题


I'm trying to make a car game that rotates the car everytime you press an arrow key. I've created the car, but everytime I try to rotate it with ctx.Rotate, the car gets stuck after moving it a specific point. It's as if the whole canvas was rotated with the car.

Car won't move anymore to the right.

Here is my code for rotating then drawing the car:

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

Here is my code for clearing the car(for refresh):

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

Logic for checking if the car reaches the edges of canvas:

Variables x and y are the car's x and y coordinates

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

Here is the link to the entire code if you need it: https://jsfiddle.net/GautamGXTV/g8v31t4r/215/


回答1:


you are actually right in that the whole canvas DOES get rotated when the car does. The quick solution to this would be saving the state of the canvas before the rotation, and then loading it after the car gets drawn. It would go something like this:

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

Also a side note, it is a good idea to use one canvas context for all your rendering, as it seems that you are currently getting 3 seperate ones. If you have any further questions, feel free to ask!



来源:https://stackoverflow.com/questions/61447725/javascript-canvas-object-gets-stuck-after-rotating-with-ctx-rotate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!