React+TypeScript手写拍照上传
以下是一个使用React和TypeScript实现的简单的拍照上传功能的示例代码:
import React, { useState } from 'react';
import { Button, Input } from 'antd';
interface Props {
// 上传图片的方法,需要在父组件中实现
uploadImage: (image: Blob) => void;
}
const CameraUpload: React.FC<Props> = ({ uploadImage }) => {
const [imageSrc, setImageSrc] = useState<string>('');
const takePhoto = async () => {
try {
const mediaStream = await navigator.mediaDevices.getUserMedia({ video: true });
const video = document.createElement('video');
video.srcObject = mediaStream;
video.play();
const canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
const ctx = canvas.getContext('2d');
if (!ctx) {
throw new Error('Canvas context error');
}
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
const image = canvas.toDataURL('image/png');
setImageSrc(image);
const blob = await fetch(image).then(r => r.blob());
uploadImage(blob);
} catch (error) {
console.error('Error while taking photo:', error);
}
};
return (
<div>
<Button onClick={takePhoto}>拍照</Button>
{imageSrc && <img src={imageSrc} alt="Uploaded Image" />}
</div>
);
};
export default CameraUpload;
在这个例子中,我们创建了一个名为CameraUpload
的React组件,它使用TypeScript作为类型系统。它有一个uploadImage
属性,这个方法需要在使用该组件的父组件中实现。takePhoto
方法负责捕获图片,将其转换为Blob,并在成功后调用uploadImage
方法。这个例子使用了Ant Design的Button
和Input
组件。
评论已关闭