我如何在不弄乱整个画布的情况下旋转js画布对象

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

我正在尝试制作一个汽车游戏,每当您按下箭头键时,汽车就会旋转。我已经创建了汽车,但是每次尝试使用ctx.Rotate旋转它时,画布都会变得混乱。

My output after rotating the car

如果我删除了使汽车旋转的代码,则游戏运行正常。Game without rotate code

这是我的代码,用于旋转并绘制汽车:

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.clearRect(0, 0, canvas.width, canvas.height);
    }

当旋转后运行程序时,它在画布中的某个点运行良好,然后停止清除,就像整个画布都在旋转一样。当它停止清理时,每次我移动时,游戏都会创建汽车的副本。这是我正在处理的代码的链接:https://jsfiddle.net/GautamGXTV/g8v31t4r/203/

我想知道如何解决此问题。...

javascript canvas jsfiddle canvasjs
1个回答
0
投票

之所以会这样,是因为clearRect方法还考虑了当前的翻译。一种解决方案是将翻译临时重置为初始翻译,然后清除,然后恢复翻译:

function clear(obj) {
    obj.save();
    obj.setTransform(1, 0, 0, 1, 0, 0);
    obj.clearRect(0, 0, canvas.width, canvas.height);
    obj.restore();
}
© www.soinside.com 2019 - 2024. All rights reserved.