0

I have an image sprite including 8 frames of my character (game hero) that is turned to right. I want that hero to be turned to left on key hold left. Now it is turned to right all the time. I am drawing the image on 2d canvas context like so:

ctx.translate(x, y);
// TODO - here I need to rotate it in 3d
// ctx.rotate();
ctx.translate(-x,-y);

ctx.drawImage(i, cycle * spriteW, 0, spriteW, spriteH, x, y, spriteW, spriteH);
ctx.restore();

Is it possible to rotate it using 2d context or do I need to change some logic?

Epsilon47
  • 768
  • 1
  • 13
  • 28

1 Answers1

1

I think you're looking for this ctx.scale(-1, 1);. But it's better to load a flipped version of your sprite when the game loads, and to switch between your left and your right sprite. This is faster than to flip the sprite.

Wout Rombouts
  • 1,479
  • 2
  • 9
  • 15
  • Thank you. Scale did not really work out for me. Maybe I used it wrong. But I used the second way you suggested - I loaded flipped spread and it works nicely. Thanks again. – Epsilon47 Apr 17 '19 at 14:12
  • You forgot to translate, and instead of storing+fetching a new image, if you are concerned by performances, generate the flipped version at the init of your app on an offscreen canvas. – Kaiido Apr 17 '19 at 23:49