Guest User

Untitled

a guest
Nov 23rd, 2017
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.84 KB | None | 0 0
  1. function onload(cb){
  2. const image = 'http://placehold.it/350x150'
  3. const img = new Image()
  4. img.src = image
  5. img.onload = () => {
  6. cb()
  7. }
  8. }
  9.  
  10. const jsdom = new JSDOM('<!doctype html><html><body></body></html>',{
  11. resources: 'usable'
  12. });
  13. const { window } = jsdom;
  14.  
  15. import CanvasImage from 'canvas/lib/image';
  16. import fs from 'fs';
  17. import path from 'path';
  18. import { URL } from 'url';
  19. import request from 'request';
  20. // Where to fetch assets on the file system when path are provided.
  21. const ASSETS_DIRECTORY = path.join(__dirname,'.');
  22.  
  23. const WindowImage = function(
  24. // Reimplemented the following class:
  25. // https://github.com/tmpvar/jsdom/blob/master/lib/jsdom/living/nodes/HTMLImageElement-impl.js
  26. // https://github.com/Automattic/node-canvas#imagesrcbuffer
  27. let source;
  28. let image;
  29. let onload;
  30. let onerror;
  31. return {
  32. set src (value) {
  33. // TODO Throw errors to the Image.onerror handler.
  34. const onDataLoaded = function (data) {
  35. image = new CanvasImage();
  36. image.onload = () => {
  37. if (onload) {
  38. onload(image);
  39. }
  40. };
  41. image.onerror = err => {
  42. if (onerror) {
  43. onerror(err);
  44. }
  45. };
  46. image.src = data;
  47. source = value;
  48. };
  49. // URL or path?
  50. let url;
  51. try {
  52. url = new URL(value);
  53. } catch (e) {}
  54. // Fetch the data.
  55. if (url) {
  56. request(url.href, (error, response, body) => {
  57. if (response && response.statusCode !== undefined && response.statusCode !== 200) {
  58. throw new Error("Status code: " + response.statusCode);
  59. }
  60. onDataLoaded(body);
  61. });
  62. } else {
  63. // Assume it is a file path: try a local file read.
  64. fs.readFile(path.join(ASSETS_DIRECTORY,value),function (err,data) {
  65. if (err) {
  66. throw err;
  67. }
  68. onDataLoaded(data);
  69. });
  70. }
  71. },
  72. set onload (handler) {
  73. onload = handler;
  74. },
  75. set onerror (handler) {
  76. onerror = handler;
  77. },
  78. get src () {
  79. return source;
  80. },
  81. // TODO Should allows to modify height and width
  82. // + add natural height and width
  83. // Cf. https://github.com/tmpvar/jsdom/blob/master/lib/jsdom/living/nodes/HTMLImageElement-impl.js#L51
  84. get width () {
  85. return image && image.width;
  86. },
  87. get height () {
  88. return image && image.height;
  89. }
  90. };
  91. };
  92.  
  93. window.Image = WindowImage;
Add Comment
Please, Sign In to add comment