Dashboard sipadu mbip
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.

useImage.js 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. "use strict";
  2. exports.__esModule = true;
  3. exports.default = useImage;
  4. var _react = require("react");
  5. /**
  6. * Fetch and load an image for programatic use such as in a `<canvas>` element.
  7. *
  8. * @param imageOrUrl The `HtmlImageElement` or image url to load
  9. * @param crossOrigin The `crossorigin` attribute to set
  10. *
  11. * ```ts
  12. * const { image, error } = useImage('/static/kittens.png')
  13. * const ref = useRef<HTMLCanvasElement>()
  14. *
  15. * useEffect(() => {
  16. * const ctx = ref.current.getContext('2d')
  17. *
  18. * if (image) {
  19. * ctx.drawImage(image, 0, 0)
  20. * }
  21. * }, [ref, image])
  22. *
  23. * return (
  24. * <>
  25. * {error && "there was a problem loading the image"}
  26. * <canvas ref={ref} />
  27. * </>
  28. * ```
  29. */
  30. function useImage(imageOrUrl, crossOrigin) {
  31. var _useState = (0, _react.useState)({
  32. image: null,
  33. error: null
  34. }),
  35. state = _useState[0],
  36. setState = _useState[1];
  37. (0, _react.useEffect)(function () {
  38. if (!imageOrUrl) return undefined;
  39. var image;
  40. if (typeof imageOrUrl === 'string') {
  41. image = new Image();
  42. image.src = imageOrUrl;
  43. if (crossOrigin) image.crossOrigin = crossOrigin;
  44. } else {
  45. image = imageOrUrl;
  46. if (image.complete && image.naturalHeight > 0) {
  47. setState({
  48. image: image,
  49. error: null
  50. });
  51. return;
  52. }
  53. }
  54. function onLoad() {
  55. setState({
  56. image: image,
  57. error: null
  58. });
  59. }
  60. function onError(error) {
  61. setState({
  62. image: image,
  63. error: error
  64. });
  65. }
  66. image.addEventListener('load', onLoad);
  67. image.addEventListener('error', onError);
  68. return function () {
  69. image.removeEventListener('load', onLoad);
  70. image.removeEventListener('error', onError);
  71. };
  72. }, [imageOrUrl, crossOrigin]);
  73. return state;
  74. }