1 import parseApng from 'apng-js';
2 import axios from 'axios';
3 import PropTypes from 'prop-types';
4 import React from 'react';
5 import { Button } from 'react-bootstrap';
6 import { useTranslation } from 'react-i18next';
8 import Icon from './Icon';
10 const createPlayer = async (apng, canvas) => {
11 const context = canvas.getContext('2d', { willReadFrequently: true });
12 const player = await apng.getPlayer(context);
17 const PngPlayer = ({ src }) => {
18 const canvas = React.useRef();
19 const { t } = useTranslation();
21 const [apng, setApng] = React.useState(null);
22 const [error, setError] = React.useState(null);
23 const [frameInfo, setFrameInfo] = React.useState('');
24 const [loading, setLoading] = React.useState(true);
25 const [player, setPlayer] = React.useState(null);
27 React.useEffect(() => {
31 const ctrl = new AbortController();
32 const fetchPng = async () => {
34 const response = await axios.get(src, {
35 responseType: 'arraybuffer',
38 const png = parseApng(response.data);
39 await png.createImages();
43 if (!axios.isCancel(e)) {
55 React.useEffect(() => {
56 if (loading || !canvas.current) return;
57 setFrameInfo(`1/${apng.frames.length}`);
59 const p = await createPlayer(apng, canvas.current);
61 const updateFrame = (number) => {
62 setFrameInfo(`${number + 1}/${apng.frames.length}`);
64 p.on('frame', updateFrame);
66 }, [apng, canvas.current, loading]);
68 const stop = React.useCallback(() => {
69 if (player) player.stop();
72 const toggle = React.useCallback(() => {
81 const nextFrame = React.useCallback(() => {
82 if (player) player.renderNextFrame();
86 return <div>Error</div>;
89 return <div>Loading</div>;
92 return <div className="png-player">
93 <div className="screen">
94 <canvas ref={canvas} width={apng.width} height={apng.height} />
96 <span className="ms-auto">{frameInfo}</span>
97 <div className="button-bar controls">
100 title={t('button.stop')}
101 variant="outline-secondary"
103 <Icon.STOP title="" />
107 title={t('button.playPause')}
108 variant="outline-secondary"
110 <Icon.PLAY title="" />
112 <Icon.PAUSE title="" />
116 title={t('button.nextFrame')}
117 variant="outline-secondary"
119 <Icon.STEP_FORWARD title="" />
125 PngPlayer.propTypes = {
126 src: PropTypes.string,
129 export default PngPlayer;