vis.js is a dynamic, browser-based visualization library
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
1.9 KiB

  1. /**
  2. * @class Images
  3. * This class loads images and keeps them stored.
  4. */
  5. function Images() {
  6. this.images = {};
  7. this.callback = undefined;
  8. }
  9. Images.prototype._resolveRelativeUrl = function(url){
  10. var img = document.createElement('img');
  11. img.src = url; // set string url
  12. url = img.src; // get qualified url
  13. img.src = null; // no server request
  14. return url;
  15. }
  16. /**
  17. * Set an onload callback function. This will be called each time an image
  18. * is loaded
  19. * @param {function} callback
  20. */
  21. Images.prototype.setOnloadCallback = function(callback) {
  22. this.callback = callback;
  23. };
  24. /**
  25. *
  26. * @param {string} url Url of the image
  27. * @param {string} url Url of an image to use if the url image is not found
  28. * @return {Image} img The image object
  29. */
  30. Images.prototype.load = function(url, brokenUrl) {
  31. var img = this.images[url];
  32. if (img === undefined) {
  33. // create the image
  34. var me = this;
  35. img = new Image();
  36. img.onload = function () {
  37. // IE11 fix -- thanks dponch!
  38. if (this.width == 0) {
  39. document.body.appendChild(this);
  40. this.width = this.offsetWidth;
  41. this.height = this.offsetHeight;
  42. document.body.removeChild(this);
  43. }
  44. if (me.callback) {
  45. me.images[url] = img;
  46. me.callback(this);
  47. }
  48. };
  49. img.onerror = function () {
  50. if (brokenUrl === undefined) {
  51. console.error("Could not load image:", url);
  52. delete this.src;
  53. if (me.callback) {
  54. me.callback(this);
  55. }
  56. }
  57. else if (this.src === me._resolveRelativeUrl(brokenUrl)){
  58. console.error("Could not load brokenImage:", brokenUrl);
  59. delete this.src;
  60. if (me.callback) {
  61. me.callback(this);
  62. }
  63. }
  64. else {
  65. this.src = brokenUrl;
  66. }
  67. };
  68. img.src = url;
  69. }
  70. return img;
  71. };
  72. module.exports = Images;