如何禁用 ctx.rotate() 对某些形状的影响?

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

我有一些我想旋转的图像和一些我不想要的图像。 首先看到这段代码:

    var mainInterval = setInterval(() => {
        ctx.clearRect(-width,-height,width,height);
        ctx.fillStyle = "green";
        ctx.fillRect(0,0,width,height);
        ctx.drawImage(pistolInv,width / 4,height - 60 * graphics,width / 8,60 * graphics);
        ctx.drawImage(submachinegunInv,width / 2,height - 60 * graphics,width / 8,60 * graphics);
        ctx.drawImage(ak47Inv,width / 4 * 3,height - 60 * graphics,width / 8,60 * graphics);
        ctx.rotate(angle);
        debugger;
        if(equippedGun != -1){
            var gun = new Image();
            gun.src = "assets/guns/" + guns[equippedGun] + ".png";
            ctx.drawImage(gun,width / 2,height / 2,120 * graphics,20 * graphics);
        }
        ctx.drawImage(player,width / 2 - (30 * graphics),height / 2 - (30 * graphics),60 * graphics,60 * graphics);
        ctx.drawImage(hand,width / 2 + (15 * graphics),height / 2 - (33 * graphics));
        ctx.drawImage(hand,width / 2 - (40 * graphics),height / 2 - (33 * graphics));
    },10);

在这个例子中,我希望前 3 个图像不旋转,第 4 个图像旋转。
但由于间隔,旧旋转将影响前 3 张图像。
我认为这是因为我旋转了整个 ctx。
如果是的话,有没有旋转形状?

javascript canvasjs
1个回答
0
投票

canvas
被转换后,所有进一步的绘图都在新的位置上 - 以前的绘图留在同一个地方。

但是,转换是堆叠的,所以一种解决方案是在绘制到转换后直接“撤消”转换。

var c = document.getElementById("cnv");
var ctx = c.getContext("2d");
var gp=0;

function animate() {

gp+=5;
gp%=360;

ctx.fillStyle='#fff'; // clear screen
ctx.fillRect(0, 0, 300, 150);

ctx.fillStyle='#f00'; // red squares
ctx.fillRect(50, 20, 10, 10);
ctx.fillRect(240, 20, 10, 10);

ctx.fillStyle='#0f0'; // gun
ctx.translate(150, 75);
ctx.rotate(gp * Math.PI / 180);
ctx.fillRect(-35,-10, 70, 20);
ctx.rotate(-gp * Math.PI / 180);
ctx.translate(-150, -75);

requestAnimationFrame(animate);

}

animate();
<canvas id="cnv" width="300" height="150" style="border:5px dashed black;border-radius:20px"></canvas>

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