演示

Camera

拍照与相册选择;移动端默认后置(environment)。

Camera

拍照与相册选择;移动端默认后置(environment)。

  • requestPermission, takePicture, pickImageFromGallery, startPreview, stopPreview
  • 离开页面时 stopPreview
TSXCamera — take / gallery
1import { useState } from "react"; 2import { Camera, toast } from "@quan-erp/shared-frontend-core"; 3 4export function PhotoActions() { 5 const [previewUrl, setPreviewUrl] = useState<string | null>(null); 6 const camera = Camera.instance; 7 8 async function takePhoto() { 9 try { 10 await camera.requestPermission(); 11 const photo = await camera.takePicture(); 12 // photo shape depends on platform (path / webPath / base64) 13 setPreviewUrl( 14 (photo as { webPath?: string; path?: string }).webPath ?? 15 (photo as { path?: string }).path ?? 16 null, 17 ); 18 } catch (e) { 19 toast.error((e as Error).message ?? "Camera failed"); 20 } 21 } 22 23 async function pickFromGallery() { 24 try { 25 await camera.requestPermission(); 26 const image = await camera.pickImageFromGallery(); 27 setPreviewUrl( 28 (image as { webPath?: string; path?: string }).webPath ?? 29 (image as { path?: string }).path ?? 30 null, 31 ); 32 } catch (e) { 33 toast.error((e as Error).message ?? "Gallery failed"); 34 } 35 } 36 37 return ( 38 <div> 39 <button type="button" onClick={() => void takePhoto()}> 40 Take photo 41 </button> 42 <button type="button" onClick={() => void pickFromGallery()}> 43 Gallery 44 </button> 45 {previewUrl ? <img src={previewUrl} alt="" /> : null} 46 </div> 47 ); 48}
TSXCamera — live preview
1import { useEffect, useRef } from "react"; 2import { Camera } from "@quan-erp/shared-frontend-core"; 3 4export function CameraPreview() { 5 const videoRef = useRef<HTMLVideoElement>(null); 6 7 useEffect(() => { 8 const camera = Camera.instance; 9 const video = videoRef.current; 10 if (!video) return; 11 12 let cancelled = false; 13 void (async () => { 14 await camera.requestPermission(); 15 if (cancelled) return; 16 await camera.startPreview(video); 17 })(); 18 19 return () => { 20 cancelled = true; 21 camera.stopPreview(); 22 }; 23 }, []); 24 25 return <video ref={videoRef} playsInline muted autoPlay />; 26}