David Hellsing
David Hellsing

Reputation: 108500

Canvas - flip half the image

I have some image data in canvas, and now I need to take the left half of the image, flip it and apply it to the right, like a mirror effect.

Example, from this:

enter image description here

To this:

enter image description here

I got this far (I have the image data ready):

ctx.drawImage(this, 0, 0, 960, 540);
var imgData = ctx.getImageData(0,0,960,540);
// loop through the data and apply mirror ??

Width & height is known. Any ideas?

Upvotes: 2

Views: 1087

Answers (1)

Cerbrus
Cerbrus

Reputation: 72857

  1. Loop through the image data
  2. If the current pixel is in the left half of the image, copy it to a position on the right:
for(var y = 0; y < height; y++) {
    for(var x = 0; x < width / 2; x++) { // divide by 2 to only loop through the left half of the image.
        var offset = ((width* y) + x) * 4; // Pixel origin

        // Get pixel
        var r = data[offset];
        var g = data[offset + 1];
        var b = data[offset + 2];
        var a = data[offset + 3];

        // Calculate how far to the right the mirrored pixel is
        var mirrorOffset = (width - (x * 2)) * 4;

        // Get set mirrored pixel's colours 
        data[offset + mirrorOffset] = r;
        data[offset + 1 + mirrorOffset] = g;
        data[offset + 2 + mirrorOffset] = b;
        data[offset + 3 + mirrorOffset] = a;
    }
}

I haven't tested this, but it should (More-or less) work, or at least give you an idea of how to do it.

Upvotes: 2

Related Questions