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

If you just flip it horizontally it will get off of bounds... so use translate to adjust its position:

ctx.translate(canvas.width, 0);
ctx.scale(-1, 1);
ctx.drawImage(img, 0, 0);

For a shorter code you can remove the translate and use the image size as negative offset in the second parameter of the drawImage (x coordinate) instead:

ctx.scale(-1, 1);
ctx.drawImage(img, canvas.width * -1, 0);

If you want to restore the context later, add save/restore before and after it all:

ctx.save();
ctx.scale(-1, 1);
ctx.drawImage(img, canvas.width * -1, 0);
ctx.restore();

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.


  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.