javascript - 在 Canvas 中翻转 Sprite

标签 javascript image canvas sprite flip

我正在使用 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/

相关文章:

javascript - 正则表达式 - 将单词集逐字匹配每个单词前后的特殊字符

javascript - 当用户手动向上或向下滚动时重置当前部分计数器

c# - 我如何知道我从流中获得的图像格式?

javascript - 使用 "open with"对话框命名从 Canvas 保存的 PNG 文件

html - 将 HTML5 Canvas 序列转换为视频文件

javascript - 在对象原型(prototype)方法中的 setInterval/setTimeout 中引用 "this"

javascript - 是否有用于仅在移动设备上消失的 Bootstrap 类?

python - 构建具有完整图像支持的 Pygame?

image - 通过 websocket 发送一个 png 图像并渲染接收到的图像

javascript - 从 svg 或通过 canvas 的 svg 输出具有正确文件名的 300 个 png 图像?