JS实现图片裁剪功能

前言

JS 实现图片的裁剪

JS 代码

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() {
//call the methods that will create a 64-bit version of thumbnail here.
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);
//place image in appropriate div
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);

// newWidth = Math.floor(newWidth);
// newHeight = Math.floor(newHeight);
// startX = Math.floor(startX);
// startY = Math.floor(startY);
/* 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 = tnCanvas.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();
}

setTimeout(function () {

}, 1000);
</script>

</html>

本文地址: https://github.com/maxzhao-it/blog/post/5949bf48/