Image image flipping by canvas (two ways)

Time:2020-11-27

Image flipping by canvas

1. Flip through canvas method

Var img = new image(); // this is the DOM object of img tag
  img.src = './sy.png';
  img.onload = function () {
    //This method is executed after the image is loaded
    ctx.drawImage(img, posx, posy, 210, 80);
  };
play.addEventListener('click', function () {
     ctx.clearRect (0, 0,  canvas.width , canvas.height ); // clear canvas
     //Displacement to do mirror flip
     ctx.translate(210+ posx * 2, 0);
     ctx.scale (- 1, 1); // Flip left and right mirror image
     
     //ctx.translate(0, 160 + posy * 2);
     // ctx.scale (1, - 1); // the upper and lower images are flipped
     ctx.drawImage(img, 0, 0, 210, 80);
  });

2. Image flipping method of pixels

//Vertical pixel inversion
    function imageDataVRevert(sourceData, newData) {
      for (var i = 0, h = sourceData.height; i < h; i++) {
        for (var j = 0, w = sourceData.width; j < w; j++) {
          newData.data[i * w * 4 + j * 4 + 0] =
            sourceData.data[(h - i) * w * 4 + j * 4 + 0];
          newData.data[i * w * 4 + j * 4 + 1] =
            sourceData.data[(h - i) * w * 4 + j * 4 + 1];
          newData.data[i * w * 4 + j * 4 + 2] =
            sourceData.data[(h - i) * w * 4 + j * 4 + 2];
          newData.data[i * w * 4 + j * 4 + 3] =
            sourceData.data[(h - i) * w * 4 + j * 4 + 3];
        }
      }
      return newData;
    }
//Horizontal pixel inversion
    function imageDataHRevert(sourceData, newData) {
      for (var i = 0, h = sourceData.height; i < h; i++) {
        for (j = 0, w = sourceData.width; j < w; j++) {
          newData.data[i * w * 4 + j * 4 + 0] =
            sourceData.data[i * w * 4 + (w - j) * 4 + 0];
          newData.data[i * w * 4 + j * 4 + 1] =
            sourceData.data[i * w * 4 + (w - j) * 4 + 1];
          newData.data[i * w * 4 + j * 4 + 2] =
            sourceData.data[i * w * 4 + (w - j) * 4 + 2];
          newData.data[i * w * 4 + j * 4 + 3] =
            sourceData.data[i * w * 4 + (w - j) * 4 + 3];
        }
      }
      return newData;
    }

Var img = new image(); // this is the DOM object of img tag
  img.src = './sy.png';
  img.onload = function () {
    //This method is executed after the image is loaded
    ctx.drawImage(img, 0, 0, 210, 80);
  };
  
    //Pixel operation
    var imgData = ctx.getImageData(0, 0, 210, 80);
    var newImgData = ctx.getImageData(0, 0, 210, 80);

    // var newImgData = ctx.getImageData(0, 0, w, h);
    ctx.putImageData (imagedatavrevert (newimgdata, imgdata), 0, 0); // flip up and down
    // ctx.putImageData (imagedatahrevelt (New imgdata, imgdata), 0, 0); // Flip left and right~~~~