Page Menu
Home
c4science
Search
Configure Global Search
Log In
Files
F99388106
useImage.js
No One
Temporary
Actions
Download File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Subscribers
None
File Metadata
Details
File Info
Storage
Attached
Created
Fri, Jan 24, 02:45
Size
1 KB
Mime Type
text/x-java
Expires
Sun, Jan 26, 02:45 (2 d)
Engine
blob
Format
Raw Data
Handle
23788254
Attached To
rOACCT Open Access Compliance Check Tool (OACCT)
useImage.js
View Options
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
;
}
Event Timeline
Log In to Comment