How to Draw a Flipped or Mirrored Image with the HTML Canvas and JavaScript?

Sometimes, we want to draw a flipped or mirrored image with the HTML canvas and JavaScript.

In this article, we’ll look at how to draw a flipped or mirrored image with the HTML canvas and JavaScript.

Draw a Flipped or Mirrored Image with the HTML Canvas and JavaScript

To draw a flipped or mirrored image with the HTML canvas and JavaScript, we can call drawImage with the width multiplied by -1 and the scale method.

For instance, we write:

<canvas></canvas>

to add the canvas element.

Then we write:

const canvas = document.querySelector('canvas')
const context = canvas.getContext('2d')
const img = new Image()
img.src = 'https://i.picsum.photos/id/943/200/200.jpg?hmac=cFvTm_QTKVRRCLsOsMx1m2RmksDL0_U5AfcmnQ7TVds'
img.onload = () => {
  context.save();
  context.scale(-1, 1);
  context.drawImage(img, 0, 0, img.width * -1, img.height);
  context.restore();
}

to select the canvas with document.querySelector.

Then we call getContext to get the context.

Next, we use the Image constructor to create an img element.

And then we set the src property of the img element to the URL of the image.

Then we set img.onload to a function that draws the image when the image is loaded.

We call scale with -1 and 1 to flip the image.

Then we call drawImage with the img image, the x and y coordinates of the top left corner, and the width and height of the image respectively.

Now we see the flipped image drawn on the screen.

Conclusion

To draw a flipped or mirrored image with the HTML canvas and JavaScript, we can call drawImage with the width multiplied by -1 and the scale method.