在画布中翻转精灵

时间:2011-10-27 16:00:14

标签: javascript image canvas 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; }
        }
    }

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

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

3 个答案:

答案 0 :(得分:34)

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

不要为您的游戏执行此操作。

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

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

答案 1 :(得分:11)

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

c.save();
c.scale(-1, 1);

将镜像上下文。绘制图像,然后

c.restore();

你可以再次正常画画。有关详细信息,请参阅https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Transformations

答案 2 :(得分:-3)

用它来翻转精灵表 http://flipapicture.com/

相关问题