var loadTimer; var imgObject = newImage(); imgObject.src = "images/fozzie.jpg"; imgObject.onLoad = onImgLoaded(); functiononImgLoaded() { if (loadTimer != null) clearTimeout(loadTimer); if (!imgObject.complete) { loadTimer = setTimeout(function () { onImgLoaded(); }, 3); } else { onPreloadComplete(); } }
注意这里我们为了演示是读取的图片文件内容,实际上除了图像文件,这里的“图像”还可以是其他形式,例如 video 元素,别的 canvas 等。
2 2. 当图片完成载入以后,重新绘制你要截取的那一部分
1 2 3 4 5 6
functiononPreloadComplete(){ //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+"" />"; }
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(); }