Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
160
rated 0 times [  165] [ 5]  / answers: 1 / hits: 18097  / 13 Years ago, thu, october 27, 2011, 12:00:00

I'm using canvas to display some sprites, and I need to flip one horizontally (so it faces left or right). I can't see any method to do that with drawImage, however.



Here's my relevant code:



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; }
}
}


As you can see, I'm using the drawImage method to draw my sprites to the canvas. The only way to flip a sprite that I can see is to flip/rotate the entire canvas, which isn't what I want to do.



Is there a way to do that? Or will I need to make a new sprite facing the other way and use that?


More From » image

 Answers
13

You can transform the canvas drawing context without flipping the entire canvas.



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


will mirror the context. Draw your image, then



c.restore();


and you can draw normally again. For more information, see https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Transformations


[#89417] Wednesday, October 26, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
piper

Total Points: 734
Total Questions: 93
Total Answers: 112

Location: Burundi
Member since Wed, Apr 6, 2022
2 Years ago
piper questions
Thu, Apr 22, 21, 00:00, 3 Years ago
Thu, Mar 11, 21, 00:00, 3 Years ago
Wed, Jun 12, 19, 00:00, 5 Years ago
Tue, Jun 11, 19, 00:00, 5 Years ago
;