JS:圖像截取部分(Image Cropping)

這裏我們討論的圖像截取部分是指從一個完整的大圖中截取一小部分出來。當然,使用js實現。

這邊文章基本整理自Cropping images with Javascript
添加了一些我的評論

例如,我們要從這樣的大圖中:

截取出

使用H5中的canvas可以簡單地解決這個問題。

1. 載入原圖像

var loadTimer;
var imgObject = new Image();
imgObject.src = 'images/fozzie.jpg';
imgObject.onLoad = onImgLoaded();
function onImgLoaded() {
  if (loadTimer != null) clearTimeout(loadTimer);
  if (!imgObject.complete) {
    loadTimer = setTimeout(function() {
      onImgLoaded();
    }, 3);
  } else {
    onPreloadComplete();
  }
}

注意這裏我們爲了演示是讀取的圖片文件內容,實際上除了圖像文件,這裏的“圖像”還可以是其他形式,例如video元素,別的canvas等。

2. 當圖片完成載入以後,重新繪製你要截取的那一部分

function onPreloadComplete(){
  //call the methods that will create a 64-bit version of thumbnail here.
  var newImg = getImagePortion(imgObject, 120, 150, 150, 80, 2);
  //place image in appropriate div
  document.getElementById("images").innerHTML = "<img alt="" src=""+newImg+"" />";
}

這個onPreloadComplete函數會在圖像載入完成以後調用。在這個函數中我們會調用實際完成圖片截取的函數getImagePortion

3. 圖像截取

getImagePortion(imgObj, newWidth, newHeight, startX, startY, ratio){
 /* the parameters: - the image element - the new width - the new height - the x point we start taking pixels - the y point we start taking pixels - the ratio */
 //set up canvas for thumbnail
 var tnCanvas = document.createElement('canvas');
 var tnCanvasContext = canvas.getContext('2d');
 tnCanvas.width = newWidth; tnCanvas.height = newHeight;
 
 /* use the sourceCanvas to duplicate the entire image. This step was crucial for iOS4 and under devices. Follow the link at the end of this post to see what happens when you don’t do this */
 var bufferCanvas = document.createElement('canvas');
 var bufferContext = bufferCanvas.getContext('2d');
 bufferCanvas.width = imgObj.width;
 bufferCanvas.height = imgObj.height;
 bufferContext.drawImage(imgObj, 0, 0);
 
 /* now we use the drawImage method to take the pixels from our bufferCanvas and draw them into our thumbnail canvas */
 tnCanvasContext.drawImage(bufferCanvas, startX,startY,newWidth * ratio, newHeight * ratio,0,0,newWidth,newHeight);
 return tnCanvas.toDataURL();
}

上面的函數時原作者給出的方法,他先將圖像完整地畫到一個canvas(bufferCanvas)上,再將這個canvas對應的目標區域畫到tnCanvas上,根據註釋來看,似乎是出於性能或者適配方面的考慮。不過就我在開發桌面端網頁時,可以直接將imgObj畫到tnCanvas上。

原文鏈接:https://www.codewoody.com/posts/2543/

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