Advertisement
Guest User

Untitled

a guest
Jun 18th, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1.  
  2. function toDataURL(src, callback) {
  3. var img = new Image();
  4. img.crossOrigin = "anonymous";
  5. img.onload = function() {
  6. var canvas = document.createElement('CANVAS');
  7. var ctx = canvas.getContext('2d');
  8. var dataURL;
  9. canvas.height = this.naturalHeight;
  10. canvas.width = this.naturalWidth;
  11. ctx.drawImage(this, 0, 0);
  12. dataURL = canvas.toDataURL();
  13. callback(dataURL);
  14. };
  15. img.src = src;
  16. if (img.complete || img.complete === undefined) {
  17. img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
  18. img.src = src;
  19. }
  20. }
  21.  
  22.  
  23. function ImageLoader(imageId, localStorageKey, imgSrc, imgAlt) {
  24. this.imgAlt = imgAlt;
  25. this.imageId = imageId;
  26. this.localStorageKey = localStorageKey;
  27. this.imgSrc = imgSrc;
  28. }
  29.  
  30. ImageLoader.prototype.loadImage = function() {
  31. console.log(this.imageId);
  32. console.log(this.localStorageKey);
  33. console.log(this.imgSrc);
  34. var that = this;
  35. var img = document.getElementById(this.imageId);
  36. if (localStorage.getItem(this.localStorageKey) !== null) {
  37. img.src = localStorage.getItem(this.localStorageKey);
  38. img.alt = this.imgAlt;
  39. console.log("Pobrałem obrazek z local storage; key: " + this.localStorageKey)
  40. } else {
  41. console.log("Przekształcam obraz "+that.imgSrc);
  42. toDataURL(
  43. that.imgSrc,
  44. function(dataUrl) {
  45. console.log("Załadowałem obrazek z sieci; adres: "+that.imgSrc);
  46. console.log(dataUrl.slice(0,100));
  47. localStorage.setItem(that.localStorageKey, dataUrl);
  48. console.log("Zapamiętałem obrazek w localStorage; key: " + that.localStorageKey);
  49. img.src=dataUrl;
  50.  
  51. }
  52. )
  53. }
  54. };
  55.  
  56. ImageLoader.prototype.clearLocalStorage = function() {
  57. localStorage.removeItem(this.localStorageKey);
  58. console.log("Wyczyściłem localStorage; klucz: " + this.localStorageKey);
  59. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement