我有一些图像,我想旋转和一些我不想要的. 首先查看以下代码:

    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.
如果是,有没有只旋转形状的方法?

推荐答案

canvas被转换后,所有进一步的绘图都在新的位置上进行-以前的绘图保持在相同的位置.

然而,变换是堆叠的,因此一种解决方案是在绘制到变换上后直接"undo撤消"变换.

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>

Javascript相关问答推荐

在分区内迭代分区

*ngFor和@代表输入decorator 和选角闭合

为什么从liveWire info js代码传递数组我出现错误?

Redux工具包查询(RTKQ)端点无效并重新验证多次触发

在观察框架中搜索CSV数据

当试图显示小部件时,使用者会出现JavaScript错误.

未捕获错误:[]:getActivePinia()被调用,但没有活动Pinia.🍍""在调用app.use(pinia)之前,您是否try 使用store ?""

如何在模块层面提供服务?

虚拟滚动实现使向下滚动可滚动到末尾

使用GraphQL查询Uniswap的ETH价格

在Matter.js中添加从点A到另一个约束的约束

WP Bootstrap NavWaker:下拉菜单一次打开所有下拉菜单

使用js构造一个html<;ath&>元素并不能使其正确呈现

将Node.js包发布到GitHub包-错误ENEEDAUTH

在D3条形图中对具有相同X值的多条记录进行分组

如何在尚未创建的鼠标悬停事件上访问和着色div?

MongoDB通过数字或字符串过滤列表

如何将字符串拆分成单词并跟踪每个单词的索引(在原始字符串中)?

如何在css中裁剪成一定Angular 的圆的一部分,而不需要复杂的多边形

我正在为我的单选按钮在HTML中设置一个值.使用Java脚本,我如何才能获得该值?