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方法将我的精灵绘制到画布上.翻转我能看到的精灵的唯一方法是翻转/旋转整个画布,这不是我想要做的.
有没有办法做到这一点?或者我是否需要以另一种方式制作新的精灵并使用它?
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