我正在尝试在 Canvas 上上传图像/视频。当用户上传图像时,它将显示在画布上;如果用户上传视频,它将显示在画布上。我可以在画布上显示图像,但无法加载视频。请检查下面的代码并帮助我解决问题。
import React, { useState, useRef, useEffect } from 'react';
const FileUpload = () => {
const [uploadedFile, setUploadedFile] = useState(null);
const fileInputRef = useRef(null);
const canvasRef = useRef(null);
const handleFileChange = (e) => {
const file = e.target.files[0];
setUploadedFile(file);
};
useEffect(() => {
if (uploadedFile) {
const canvas = canvasRef.current;
const context = canvas.getContext('2d');
const mediaElement = document.createElement(
uploadedFile.type.startsWith('image/') ? 'img' : 'video'
);
mediaElement.src = URL.createObjectURL(uploadedFile);
mediaElement.onload = () => {
context.clearRect(0, 0, canvas.width, canvas.height);
// For videos, play the video and update the canvas during playback
if (uploadedFile.type.startsWith('video/')) {
mediaElement.addEventListener('timeupdate', () => {
context.drawImage(
mediaElement,
0,
0,
canvas.width,
canvas.height
);
});
mediaElement.play().catch((error) => {
console.error('Error playing video:', error);
});
} else {
// For images
context.drawImage(
mediaElement,
0,
0,
canvas.width,
canvas.height
);
}
};
}
}, [uploadedFile]);
return (
<div className="App">
<input type="file" ref={fileInputRef} onChange={handleFileChange} accept="image/*,video/*" />
<canvas ref={canvasRef} width={460} height={300} style={{ marginTop: '20px' }} />
</div>
);
};
export default FileUpload;
您只能将视频添加到带有控件和 src 的标签,例如:
<video controls ref={canvasRef} src={canvasRef}/>
要么使用 iframe。无论你想做什么都不会成功。