-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
directives.js
62 lines (47 loc) · 1.9 KB
/
directives.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
'use strict';
angular
.module('app')
// Angular File Upload module does not include this directive
// Only for example
/**
* The ng-thumb directive
* @author: nerv
* @version: 0.1.2, 2014-01-09
*/
.directive('ngThumb', ['$window', function($window) {
var helper = {
support: !!($window.FileReader && $window.CanvasRenderingContext2D),
isFile: function(item) {
return angular.isObject(item) && item instanceof $window.File;
},
isImage: function(file) {
var type = '|' + file.type.slice(file.type.lastIndexOf('/') + 1) + '|';
return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
}
};
return {
restrict: 'A',
template: '<canvas/>',
link: function(scope, element, attributes) {
if (!helper.support) return;
var params = scope.$eval(attributes.ngThumb);
if (!helper.isFile(params.file)) return;
if (!helper.isImage(params.file)) return;
var canvas = element.find('canvas');
var reader = new FileReader();
reader.onload = onLoadFile;
reader.readAsDataURL(params.file);
function onLoadFile(event) {
var img = new Image();
img.onload = onLoadImage;
img.src = event.target.result;
}
function onLoadImage() {
var width = params.width || this.width / this.height * params.height;
var height = params.height || this.height / this.width * params.width;
canvas.attr({ width: width, height: height });
canvas[0].getContext('2d').drawImage(this, 0, 0, width, height);
}
}
};
}]);