Skip to content

Commit b484030

Browse files
author
Sergey Russkih
committed
fix croping
1 parent 88bd98b commit b484030

File tree

2 files changed

+19
-119
lines changed

2 files changed

+19
-119
lines changed

index.html

Lines changed: 0 additions & 106 deletions
This file was deleted.

load-image.js

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -62,20 +62,20 @@
6262
var canvas = document.createElement('canvas'),
6363
width = img.width,
6464
height = img.height,
65-
x = 0, y = 0,
65+
x = 0, y = 0, dx = 0, dy = 0,
6666
scale;
6767

6868
// if crop in options then we have to get biggest scale factor
6969
if (options.crop || false){
7070
scale = Math.max(
71-
(options.width) / width,
72-
(options.height) / height
71+
(options.width || width) / width,
72+
(options.height || height) / height
7373
);
7474
} else {
7575
// else we have to get lowest
7676
scale = Math.min(
77-
(options.width) / width,
78-
(options.height) / height
77+
(options.width || width) / width,
78+
(options.height || height) / height
7979
);
8080
}
8181

@@ -86,24 +86,30 @@
8686
height = parseInt(height * scale, 10);
8787
}
8888

89+
// if need to crop, then
8990
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);
9294

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
9697
if (dx || dy) {
9798
x = -1 * parseInt(dx / 2, 10);
9899
y = -1 * parseInt(dy / 2, 10);
99100
}
100101
}
101102

102103
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;
105108
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+
);
107113
return canvas;
108114
}
109115

0 commit comments

Comments
 (0)