我正在使用 Canvas 来显示一些 Sprite ,并且我需要水平翻转一个 Sprite (因此它面向左或向右)。但是,我看不到任何使用 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
方法将 Sprite 绘制到 Canvas 上。翻转我能看到的 Sprite 的唯一方法是翻转/旋转整个 Canvas ,这不是我想要做的。
有办法做到这一点吗?或者我需要制作一个面向另一个方向的新 Sprite 并使用它?
最佳答案
虽然 Gaurav 展示了在 Canvas 中翻转 Sprite 的技术方法......
请勿对您的游戏执行此操作。
而是制作第二张图像(或使当前图像更大),它是恶意表的翻转版本。 “翻转上下文并绘制图像”与“仅绘制图像”之间的性能差异可能很大。在 Opera 和 Safari 中,翻转 Canvas 会导致绘图速度慢十倍,而在 Chrome 中则慢两倍。请参阅this jsPerf举个例子。
预先计算翻转的 Sprite 总是会更快,并且在游戏中 Canvas 性能确实很重要。
关于javascript - 在 Canvas 中翻转 Sprite ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7918803/