canvas2dtransformation

CanvasRenderingContext2D flip transformation


I found this CanvasRenderingContext2D and i played around a little bit with it. I was able to scale and to rotate my Image using this context:

crop: function () {
    var canvas = document.createElement("canvas");
    var context = canvas.getContext("2d");

    canvas.width = this.options.width / this.scale;
    canvas.height = this.options.height / this.scale;

    var currWidth = this.imgWidth * this.scale;
    var currHeight = this.imgHeight * this.scale;
    var correctX = (currWidth - this.imgWidth) / 2;
    var correctY = (currHeight - this.imgHeight) / 2;
    var sourceX = (this.posX - correctX) / this.scale;
    var sourceY = (this.posY - correctY) / this.scale;

    context.translate(sourceX, sourceY);
    context.translate(this.imgWidth / 2, this.imgHeight / 2);
    context.rotate(this.rotate * Math.PI / 180);
    context.drawImage(this.imgFull, this.imgWidth / 2 * -1, this.imgHeight / 2 * -1);

    this.options.modal.remove();
    this.promise.resolve(canvas);
},

Unfortunately i could not find any function to flip the canvas vertically or horizontally. In code i thought i could do something like:

if(self.flipV) {
    context.rotateY(180);
}

if(self.flipH) {
    context.rotateX(180);
}

But i could not find any methods for rotating on the y- or x-axis. Is there any way i could perform my flip transformation here?


Solution

  • Although it's not obvious, you can flip using the context.scale method.

    Flip horizontally with context.scale(-1,1) and flip vertically with context.scale(1,-1).

    Just like with rotation, you must set the rotation point using context.translate before doing your context.scale.

    enter image description here

    Here's example code and a Demo:

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    
    var img=new Image();
    img.onload=start;
    img.src="https://dl.dropboxusercontent.com/u/139992952/multple/marioRunningRight.png";
    function start(){
    
      // original
      ctx.drawImage(img,200,200);
    
      // horizontal flip
      ctx.translate(200,0);
      ctx.scale(-1,1);
      ctx.drawImage(img,0,200);
      ctx.setTransform(1,0,0,1,0,0);
    
      // vertical flip
      ctx.translate(0,200);
      ctx.scale(1,-1);
      ctx.drawImage(img,200,0);
      ctx.setTransform(1,0,0,1,0,0);
    
      // labels
      ctx.font='18px verdana';
      ctx.textAlign='center';
      ctx.fillText('Original',275,375);
      ctx.fillText('scale(-1,1)',125,375);
      ctx.fillText('Horizontal Flip',125,395);
      ctx.fillText('scale(1,-1)',275,20);
      ctx.fillText('Vertical Flip',275,40);
    }
    <canvas id="canvas" width=400 height=425></canvas>