3

I have a problem with following: My canvas element (1280x720) needs to get mirrored horizontally and rotated to 180 degrees. After that, the canvas becomes an base64 image (works without problems).

I tried:

var ctx =meinElement.getContext('2d');
meinElement.width = 1280;
meinElement.height = 720;
ctx.scale(-1, 1);
ctx.translate(meinElement.width-1,   meinElement.height-1);
ctx.rotate(Math.PI);
ctx.drawImage(video, 0, 0, meinElement.width, meinElement.height);

The rotation works like a charm, but the mirroring causes an black element - no matter if I rotate or mirror first - does someone have an idea?

Thanks a lot!

Polaris
  • 712
  • 7
  • 21

1 Answers1

8

setTransform(1,0,0,-1,0,canvas.height);

Use setTransform it takes 6 numbers. The first 2 are the direction and scale of the x axis in pixels. By default it is 1,0. The next two are the direction and scale of the y axis. By default it is 0,1. The last two are the origin. Where on the canvas something will be drawn if you draw at 0,0. By default it is at 0,0 top left.

Rotating the canvas 180 will flip both the x and y axis. the x axis goes from 1,0 to -1,0 and y axis from 0,1 to 0,-1.

To mirror on the x axis just reverse x component of the x Axis thus the rotated -1,0 mirrors to 1,0.

Now we need to set the origin. The x axis moves from left to right as normal 1,0 so the x origin is on the left at 0. The y axis moves from bottom up thus the origin needs to be at the bottom of the canvas.

The result then is

ctx.setTransform(1,0,0,-1,0,canvas.height);
ctx.drawImage(0,0)

BTW rotate 180 then mirror X is the same as just mirror Y.

Community
  • 1
  • 1
Blindman67
  • 51,134
  • 11
  • 73
  • 136