UNPKG

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