mirror of
https://github.com/idanoo/GoScrobble.git
synced 2024-11-24 17:35:16 +00:00
78 lines
1.7 KiB
JavaScript
78 lines
1.7 KiB
JavaScript
|
import { useState, useEffect } from 'react';
|
||
|
|
||
|
/**
|
||
|
* Fetch and load an image for programatic use such as in a `<canvas>` element.
|
||
|
*
|
||
|
* @param imageOrUrl The `HtmlImageElement` or image url to load
|
||
|
* @param crossOrigin The `crossorigin` attribute to set
|
||
|
*
|
||
|
* ```ts
|
||
|
* const { image, error } = useImage('/static/kittens.png')
|
||
|
* const ref = useRef<HTMLCanvasElement>()
|
||
|
*
|
||
|
* useEffect(() => {
|
||
|
* const ctx = ref.current.getContext('2d')
|
||
|
*
|
||
|
* if (image) {
|
||
|
* ctx.drawImage(image, 0, 0)
|
||
|
* }
|
||
|
* }, [ref, image])
|
||
|
*
|
||
|
* return (
|
||
|
* <>
|
||
|
* {error && "there was a problem loading the image"}
|
||
|
* <canvas ref={ref} />
|
||
|
* </>
|
||
|
* ```
|
||
|
*/
|
||
|
export default function useImage(imageOrUrl, crossOrigin) {
|
||
|
var _useState = useState({
|
||
|
image: null,
|
||
|
error: null
|
||
|
}),
|
||
|
state = _useState[0],
|
||
|
setState = _useState[1];
|
||
|
|
||
|
useEffect(function () {
|
||
|
if (!imageOrUrl) return undefined;
|
||
|
var image;
|
||
|
|
||
|
if (typeof imageOrUrl === 'string') {
|
||
|
image = new Image();
|
||
|
if (crossOrigin) image.crossOrigin = crossOrigin;
|
||
|
image.src = imageOrUrl;
|
||
|
} else {
|
||
|
image = imageOrUrl;
|
||
|
|
||
|
if (image.complete && image.naturalHeight > 0) {
|
||
|
setState({
|
||
|
image: image,
|
||
|
error: null
|
||
|
});
|
||
|
return;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
function onLoad() {
|
||
|
setState({
|
||
|
image: image,
|
||
|
error: null
|
||
|
});
|
||
|
}
|
||
|
|
||
|
function onError(error) {
|
||
|
setState({
|
||
|
image: image,
|
||
|
error: error
|
||
|
});
|
||
|
}
|
||
|
|
||
|
image.addEventListener('load', onLoad);
|
||
|
image.addEventListener('error', onError);
|
||
|
return function () {
|
||
|
image.removeEventListener('load', onLoad);
|
||
|
image.removeEventListener('error', onError);
|
||
|
};
|
||
|
}, [imageOrUrl, crossOrigin]);
|
||
|
return state;
|
||
|
}
|