1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| <html>
<body> <div id="images" style="width:100px;height:200px;"></div> <img src="3.jpg"/>
</body> <script> var loadTimer; var imgObject = new Image(); imgObject.src = '3.jpg'; imgObject.onLoad = onImgLoaded(); console.log('imgObject.naturalHeight==============>', imgObject.naturalHeight); console.log('imgObject.naturalWidth==============>', imgObject.naturalWidth);
function onImgLoaded() { if (loadTimer != null) clearTimeout(loadTimer); if (!imgObject.complete) { loadTimer = setTimeout(function () { onImgLoaded(); }, 3); } else { onPreloadComplete(); } }
function onPreloadComplete() { var newImg = getImagePortion(imgObject, 0.17443209886550903* imgObject.naturalWidth, 0.1213589534163475 * imgObject.naturalHeight, 0.44079777598381042 * imgObject.naturalWidth, 0.44744855165481567 * imgObject.naturalHeight, 2); console.log("newImg", newImg); document.getElementById("images").innerHTML = "<img alt=\"\" src=\"" + newImg + "\" />"; }
function getImagePortion(imgObj, newWidth, newHeight, startX, startY, ratio) { console.log('newWidth', newWidth); console.log('newHeight', newHeight); console.log('startX', startX); console.log('startY', startY);
var tnCanvas = document.createElement('canvas'); var tnCanvasContext = tnCanvas.getContext('2d'); tnCanvas.width = newWidth; tnCanvas.height = newHeight;
var bufferCanvas = document.createElement('canvas'); var bufferContext = bufferCanvas.getContext('2d'); bufferCanvas.width = imgObj.width; bufferCanvas.height = imgObj.height; bufferContext.drawImage(imgObj, 0, 0);
tnCanvasContext.drawImage(bufferCanvas, startX, startY, newWidth * ratio, newHeight * ratio, 0, 0, newWidth, newHeight); return tnCanvas.toDataURL(); }
setTimeout(function () {
}, 1000); </script>
</html>
|