1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- import React, { useState, useRef } from 'react';
- import { Button } from 'antd'
- import Upload from './Upload';
- import { uplodeNoteImage } from '@/services/note'
- import styles from './style.less';
- import { useEffect } from 'react';
-
- function beforeUpload(file) {
- const isMp4 = file.type === 'video/mp4';
- if (!isMp4) {
- message.error('请上传 MP4 视频!');
- }
-
- return isMp4;
- }
-
- export default (props) => {
- //onPoster 改变主图事件 isScreenshot判断父组件是否需要截屏按钮
- const { value, onChange, onPoster, isScreenshot } = props;
- const [loading, setLoading] = useState(false);//上传按钮loading框
- const [capturing, setCapturing] = useState(false);//截屏按钮loading框
- const [video, setVideo] = useState()//当前上传的视频
- const [isVideoReady, setIsVideoReady] = useState(false)//判断视频是否加载成功
-
- const canvasRef = useRef()
- const videoRef = useRef()
-
- useEffect(() => {
- setVideo(value)//父组件的视频获取成功时改变当前页面的视频
- }, [value])
-
- const handleChange = info => {
- if (info.file.status === 'uploading') {
- setLoading(true);
- return;
- }
- if (info.file.status === 'error') {
- setLoading(false);
- return;
- }
- if (info.file.status === 'done') {
- onChange(info.file.response);
- setLoading(false);
- }
- };
-
- //开始截图
- const handelScreenshot = () => {
- const ctx = canvasRef.current.getContext("2d");
- ctx.drawImage(videoRef.current, 0, 0);
- const image = canvasRef.current.toDataURL("image/png", 0.9)
- setCapturing(true)
- uplodeNoteImage({ base64: image }).then((res) => {
- onPoster(res)
- setCapturing(false)
- })
- }
-
- //视频加载成功事件
- const handleVideoReady = (e) => {
- setIsVideoReady(true)
- canvasRef.current.width = e.target.videoWidth;
- canvasRef.current.height = e.target.videoHeight;
- }
-
- return (
- <div className={styles['video-uploader']}>
- <Upload
- className="image-uploader"
- showUploadList={false}
- beforeUpload={beforeUpload}
- onChange={handleChange}
- >
- <div style={{ maxWidth: '1px', maxHeight: '1px', overflow: 'hidden' }}>
- <canvas ref={canvasRef}></canvas>
- </div>
- <Button loading={loading}>
- 点击上传视频 (MP4)
- </Button>
-
- </Upload>
- {
- isScreenshot && (
- // disabled={!isVideoReady} 当视频准备成功时截屏按钮可以点击 否则不能点击
- <Button loading={capturing} style={{ marginLeft: '1em' }} onClick={handelScreenshot} disabled={!isVideoReady}>截屏</Button>
- )
- }
- {
- !!video && (
- <video ref={videoRef} width="320" height='500' crossOrigin='anonymous' controls src={video} onCanPlay={handleVideoReady}></video>
- )
- }
- </div>
- );
- }
|