Dashboard sipadu mbip
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

useImage.js 1.7KB

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