Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML Canvas: How to draw a flipped/mirrored image?

I'm trying to flip/mirror an image as I paint it on an HTML canvas; I found a game tutorial showing a sprite sheet per direction a character has to face, but this doesn't seem quite right to me. Especially since each frame has a different size.

What would be the best technique to reach this goal?

I tried to call the setScale(-1, 1); on my canvas with no success. Maybe that isn't meant for this.

Thanks

like image 692
Jem Avatar asked Nov 17 '11 13:11

Jem


People also ask

How do I flip an image in HTML canvas?

You can flip an Image using HTML5 like this: // flip x axis ctx. scale(-1, 1); ctx. drawImage(img, x, y); // flip it back again ctx.

How do you flip an image on canvas?

Tap the element you want to flip. On the toolbar below the editor, tap on Flip. You may have to swipe through the toolbar to see the Flip icon. Tap on Flip horizontal to flip it sideways, or Flip vertical to flip it upside down.

How do you flip a canvas vertically?

In the top menu bar, select Image –> Image Rotation –> Flip Canvas Horizontal/Flip Canvas Vertical. You can do a quick image flip in just one click.

How do you flip a drawing in JavaScript?

Use JavaScript rotate() method to rotate a drawing object on a canvas.


2 Answers

  1. You can do this by transforming the context with myContext.scale(-1,1) before drawing your image, however

  2. This is going to slow down your game. It's a better idea to have a separate, reversed sprite.

like image 84
Phrogz Avatar answered Sep 20 '22 20:09

Phrogz


You need to set the scale of the canvas as well as inverting the width.

drawToCanvas : function(v, context, width, height){     context.save();     context.scale(-1, 1);     context.drawImage(v, 0, 0, width*-1, height);     context.restore(); } 

There are probably some performance issues with this but for me that was not an issue.

like image 22
digitaltag Avatar answered Sep 20 '22 20:09

digitaltag