pasteImage.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /* eslint-disable */
  2. // ------------------------------------------------------------------------
  3. // Created by STRd6
  4. // MIT License
  5. // https://github.com/distri/jquery-image_reader/blob/master/paste.coffee.md
  6. //
  7. // Raymond re-write it to javascript
  8. (function($) {
  9. $.event.fix = (function(originalFix) {
  10. return function(event) {
  11. event = originalFix.apply(this, arguments);
  12. if (event.type.indexOf('copy') === 0 || event.type.indexOf('paste') === 0) {
  13. event.clipboardData = event.originalEvent.clipboardData;
  14. }
  15. return event;
  16. };
  17. })($.event.fix);
  18. const defaults = {
  19. callback: $.noop,
  20. matchType: /image.*/,
  21. };
  22. return $.fn.pasteImageReader = function(options) {
  23. if (typeof options === 'function') {
  24. options = {
  25. callback: options,
  26. };
  27. }
  28. options = $.extend({}, defaults, options);
  29. return this.each(function() {
  30. const element = this;
  31. return $(element).bind('paste', function(event) {
  32. const types = event.clipboardData.types;
  33. const items = event.clipboardData.items;
  34. for(let i=0; i<types.length; i++) {
  35. if(types[i].match(options.matchType) || items[i].type.match(options.matchType)) {
  36. const f = items[i].getAsFile();
  37. const reader = new FileReader();
  38. reader.onload = function(evt) {
  39. return options.callback.call(element, {
  40. dataURL: evt.target.result,
  41. event: evt,
  42. file: f,
  43. name: f.name,
  44. });
  45. };
  46. reader.readAsDataURL(f);
  47. return;
  48. }
  49. }
  50. });
  51. });
  52. };
  53. })(jQuery);