在画布中翻转精灵

Jam*_*son 20 javascript canvas image sprite flip

我正在使用画布来显示一些精灵,我需要水平翻转一个(所以它面向左或右).但是,我无法看到任何方法drawImage.

这是我的相关代码:

this.idleSprite = new Image();
this.idleSprite.src = "/game/images/idleSprite.png";
this.idleSprite.frameWidth = 28;
this.idleSprite.frameHeight = 40;
this.idleSprite.frames = 12;
this.idleSprite.frameCount = 0;

this.draw = function() {
        if(this.state == "idle") {
            c.drawImage(this.idleSprite, this.idleSprite.frameWidth * this.idleSprite.frameCount, 0, this.idleSprite.frameWidth, this.idleSprite.frameHeight, this.xpos, this.ypos, this.idleSprite.frameWidth, this.idleSprite.frameHeight);
            if(this.idleSprite.frameCount < this.idleSprite.frames - 1) { this.idleSprite.frameCount++; } else { this.idleSprite.frameCount = 0; }
        } else if(this.state == "running") {
            c.drawImage(this.runningSprite, this.runningSprite.frameWidth * this.runningSprite.frameCount, 0, this.runningSprite.frameWidth, this.runningSprite.frameHeight, this.xpos, this.ypos, this.runningSprite.frameWidth, this.runningSprite.frameHeight);
            if(this.runningSprite.frameCount < this.runningSprite.frames - 1) { this.runningSprite.frameCount++; } else { this.runningSprite.frameCount = 0; }
        }
    }
Run Code Online (Sandbox Code Playgroud)

如您所见,我正在使用该drawImage方法将我的精灵绘制到画布上.翻转我能看到的精灵的唯一方法是翻转/旋转整个画布,这不是我想要做的.

有没有办法做到这一点?或者我是否需要以另一种方式制作新的精灵并使用它?

Sim*_*ris 34

虽然Gaurav已经展示了在画布上翻转精灵的技术方法......

不要为你的游戏做这件事.

而是制作第二张图像(或使当前图像变大),这是一张翻版的版画."翻转上下文和绘制图像"与"仅绘制图像"之间的性能差异可能很大.在Opera和Safari中,翻转画布会导致绘图速度慢十倍,而在Chrome中速度则慢两倍.有关示例,请参阅此jsPerf.

预先计算你翻转的精灵总是会更快,而在游戏画布中,性能非常重要.


Gau*_*rav 11

您可以在不翻转整个画布的情况下变换画布绘图上下文.

c.save();
c.scale(-1, 1);
Run Code Online (Sandbox Code Playgroud)

将反映上下文.然后绘制你的图像

c.restore();
Run Code Online (Sandbox Code Playgroud)

你可以再画一遍.有关更多信息,请参阅https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Transformations

  • 谢谢!但由于西蒙的回答,我将使用他的技术.我会把你的标记作为接受的答案,因为它正在回答我的问题:) (2认同)