canvas 根據像素實現圖像垂直,水平翻轉

轉載自:https://blog.csdn.net/u011539729/article/details/102874601

 

假設這有一張養眼圖片,它長這樣

接着我想把照片垂直翻轉一下,變成這樣

 

翻轉後體驗了一把倒立的美女. 經過對比,垂直翻轉後,上邊和下邊都互換了過來,也就是說,上邊的像素根據垂直中軸對稱和下邊的像素進行了互換操作,垂直翻轉的關鍵點就是每一列的上下像素根據軸對稱,確實很簡單,以下是實現的步驟
1.獲取畫布上圖像的像素信息
2.遍歷總行數一半的每一行作爲外循環(向下取整)
3.遍歷當前行的列作爲內循環,把列的每個通道按照水平軸對稱和鏡像裏的通道互換
4.把處理後的像素信息放回畫布
現在知道怎麼做了,繼續

function Filter(context){
  this.context = context;
}
Filter.prototype.constructor = Filter;
Filter.prototype.flipVertical = function(startX, startY, w, h){
  // 1.獲取圖像信息
  let imgdata = this.context.getImageData(startX, startY, w, h);
  let middleAxle /*中軸*/ = Math.floor(h / 2),
      rowAisles = w * 4;

  // 2.遍歷總行數一半的每一行作爲外循環(向下取整)
  for (var curRow = 0; curRow < middleAxle; curRow++) {
    // 
    let aisleStart /*開始的通道位置*/ = curRow * rowAisles,
        mirrorStart /*中軸對稱的開始位置*/ = (h - curRow - 1) * rowAisles;
    
    // 3.遍歷當前行的列作爲內循環,把列的每個通道按照水平軸對稱和鏡像裏的通道互換
    for (; aisleStart < rowAisles * (curRow + 1); aisleStart += 4, mirrorStart += 4) {
      var tr = imgdata.data[aisleStart],
        tg = imgdata.data[aisleStart + 1],
        tb = imgdata.data[aisleStart + 2],
        ta = imgdata.data[aisleStart + 3];

      imgdata.data[aisleStart] = imgdata.data[mirrorStart];
      imgdata.data[aisleStart + 1] = imgdata.data[mirrorStart + 1];
      imgdata.data[aisleStart + 2] = imgdata.data[mirrorStart + 2];
      imgdata.data[aisleStart + 3] = imgdata.data[mirrorStart + 3];

      imgdata.data[mirrorStart] = tr;
      imgdata.data[mirrorStart + 1] = tg;
      imgdata.data[mirrorStart + 2] = tb;
      imgdata.data[mirrorStart + 3] = ta;
    }
  }

  // 4.把處理後的像素信息放回畫布
  this.context.clearRect(startX, startY, w, h);
  this.context.putImageData(imgdata, startX, startY);
}

接着對預先渲染到畫布上的圖像,一頓操作猛如虎,調用flipVertical方法,大功告成! 查看示例(flipVertical)

示例Github:https://github.com/Xlipotter/dispose-graphic

總結一下:圖像的翻轉其實是對圖像每個像素的通道按照一定的規則(這裏規則是上下顛倒)重新排列).

The End~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章