Image Drop

Drag and drop images onto the canvas to load them

  1. // ==UserScript==
  2. // @name Image Drop
  3. // @version 1.2
  4. // @description Drag and drop images onto the canvas to load them
  5. // @author Bell
  6. // @namespace https://greasyfork.org/users/281093
  7. // @match https://sketchful.io/
  8. // @grant none
  9. // jshint esversion: 6
  10. // ==/UserScript==
  11.  
  12. document.querySelector('#private').style.display = 'inline';
  13. const sketchCanvas = document.querySelector('#canvas');
  14. const sketchCtx = sketchCanvas.getContext('2d');
  15.  
  16. sketchCanvas.addEventListener('dragenter', highlight, false);
  17. sketchCanvas.addEventListener('dragleave', unhighlight, false);
  18. sketchCanvas.addEventListener('drop', handleDrop, false);
  19. sketchCanvas.addEventListener('dragover', function(event) {
  20. event.preventDefault();
  21. }, false);
  22.  
  23. sketchCanvas.save = () => {
  24. canvas.dispatchEvent(new MouseEvent('pointerup', {
  25. bubbles: true,
  26. clientX: 0,
  27. clientY: 0,
  28. button: 0
  29. }));
  30. };
  31.  
  32. function handleDrop(e) {
  33. e.preventDefault();
  34. sketchCanvas.style.filter = '';
  35. const dt = e.dataTransfer;
  36. const files = dt.files;
  37.  
  38. if (files.length && files !== null) {
  39. handleFiles(files);
  40. }
  41. }
  42.  
  43. function handleFiles(files) {
  44. ([...files]).forEach(previewFile);
  45. }
  46.  
  47. function previewFile(file) {
  48. const reader = new FileReader();
  49. reader.readAsDataURL(file);
  50. reader.onloadend = () => {
  51. const img = document.createElement('img');
  52. img.src = reader.result;
  53. img.onload = () => { loadImage(img); };
  54. };
  55. }
  56.  
  57. function loadImage(img) {
  58. if (img.height && img !== null && sketchCanvas.height) {
  59. const heightRatio = img.height / sketchCanvas.height;
  60.  
  61. // Scale the image to fit the canvas
  62. if (heightRatio && heightRatio != 1) {
  63. img.height /= heightRatio;
  64. img.width /= heightRatio;
  65. }
  66.  
  67. // Center the image
  68. const startX = Math.floor(sketchCanvas.width / 2 - img.width / 2);
  69.  
  70. sketchCtx.drawImage(img, startX, 0, img.width, img.height);
  71. sketchCanvas.save();
  72. }
  73. }
  74.  
  75. function highlight(e) {
  76. e.preventDefault();
  77. sketchCanvas.style.filter = 'brightness(0.5)';
  78. }
  79.  
  80. function unhighlight(e) {
  81. e.preventDefault();
  82. sketchCanvas.style.filter = '';
  83. }