|
62 | 62 | var canvas = document.createElement('canvas'),
|
63 | 63 | width = img.width,
|
64 | 64 | height = img.height,
|
65 |
| - x = 0, y = 0, |
| 65 | + x = 0, y = 0, dx = 0, dy = 0, |
66 | 66 | scale;
|
67 | 67 |
|
68 | 68 | // if crop in options then we have to get biggest scale factor
|
69 | 69 | if (options.crop || false){
|
70 | 70 | scale = Math.max(
|
71 |
| - (options.width) / width, |
72 |
| - (options.height) / height |
| 71 | + (options.width || width) / width, |
| 72 | + (options.height || height) / height |
73 | 73 | );
|
74 | 74 | } else {
|
75 | 75 | // else we have to get lowest
|
76 | 76 | scale = Math.min(
|
77 |
| - (options.width) / width, |
78 |
| - (options.height) / height |
| 77 | + (options.width || width) / width, |
| 78 | + (options.height || height) / height |
79 | 79 | );
|
80 | 80 | }
|
81 | 81 |
|
|
86 | 86 | height = parseInt(height * scale, 10);
|
87 | 87 | }
|
88 | 88 |
|
| 89 | + // if need to crop, then |
89 | 90 | if (options.crop || false){
|
90 |
| - var dx = width - Math.min(width, options.width || width), |
91 |
| - dy = height - Math.min(height, options.height || height); |
| 91 | + // we have to get difference between required size and image size |
| 92 | + dx = width - Math.min(width, options.width || width); |
| 93 | + dy = height - Math.min(height, options.height || height); |
92 | 94 |
|
93 |
| - // if we have difference with required size and |
94 |
| - // currently calculated size, we have to calculate |
95 |
| - // image offset to got correct croping |
| 95 | + // if we have difference is, then we have to get |
| 96 | + // image offset in canvas, to crop the image correctly |
96 | 97 | if (dx || dy) {
|
97 | 98 | x = -1 * parseInt(dx / 2, 10);
|
98 | 99 | y = -1 * parseInt(dy / 2, 10);
|
99 | 100 | }
|
100 | 101 | }
|
101 | 102 |
|
102 | 103 | if (img.getContext || (options.canvas && canvas.getContext)) {
|
103 |
| - canvas.width = width; |
104 |
| - canvas.height = height; |
| 104 | + // if was have to crop our image, thne we have use |
| 105 | + // required image sizes for canvas |
| 106 | + canvas.width = width - dx; |
| 107 | + canvas.height = height - dy; |
105 | 108 | canvas.getContext('2d')
|
106 |
| - .drawImage(img, x, y, width, height); |
| 109 | + .drawImage(img, |
| 110 | + 0, 0, img.width, img.height, |
| 111 | + x, y, width, height |
| 112 | + ); |
107 | 113 | return canvas;
|
108 | 114 | }
|
109 | 115 |
|
|
0 commit comments