directives.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. 'use strict';
  2. angular
  3. .module('app')
  4. // Angular File Upload module does not include this directive
  5. // Only for example
  6. /**
  7. * The ng-thumb directive
  8. * @author: nerv
  9. * @version: 0.1.2, 2014-01-09
  10. */
  11. .directive('ngThumb', ['$window', function($window) {
  12. var helper = {
  13. support: !!($window.FileReader && $window.CanvasRenderingContext2D),
  14. isFile: function(item) {
  15. return angular.isObject(item) && item instanceof $window.File;
  16. },
  17. isImage: function(file) {
  18. var type = '|' + file.type.slice(file.type.lastIndexOf('/') + 1) + '|';
  19. return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
  20. }
  21. };
  22. return {
  23. restrict: 'A',
  24. template: '<canvas/>',
  25. link: function(scope, element, attributes) {
  26. if (!helper.support) return;
  27. var params = scope.$eval(attributes.ngThumb);
  28. if (!helper.isFile(params.file)) return;
  29. if (!helper.isImage(params.file)) return;
  30. var canvas = element.find('canvas');
  31. var reader = new FileReader();
  32. reader.onload = onLoadFile;
  33. reader.readAsDataURL(params.file);
  34. function onLoadFile(event) {
  35. var img = new Image();
  36. img.onload = onLoadImage;
  37. img.src = event.target.result;
  38. }
  39. function onLoadImage() {
  40. var width = params.width || this.width / this.height * params.height;
  41. var height = params.height || this.height / this.width * params.width;
  42. canvas.attr({ width: width, height: height });
  43. canvas[0].getContext('2d').drawImage(this, 0, 0, width, height);
  44. }
  45. }
  46. };
  47. }]);