UNPKG

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