动态获取视频中多个时间点的图片,react 18 实现 -cursor

120 阅读1分钟

// Welcome to Cursor

// 1. Try generating with command K on a new line. Ask for a new react component of an error popup. // 2. Then, select the outputted code and hit chat. Ask if there's a bug. Ask how to improve. // 3. Try selecting some code and hitting edit. Ask the bot to add a button that updates a statefield. // 4. To try out cursor on your own projects, go to file menu (top left) and open a folder. // To dynamically capture an image at a certain frame rate from a video, you can use the HTML5 video element and the canvas element in React 18.

import React, { useRef, useState } from 'react';

function VideoCapture() {
  const videoRef = useRef(null);
  const canvasRef = useRef(null);
  const [capturedImages, setCapturedImages] = useState([]);

  const captureImage = (time) => {
    const video = videoRef.current;
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    video.currentTime = time;
    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
    const image = canvas.toDataURL();
    setCapturedImages([...capturedImages, image]);
  };

  return (
    <div>
      <video ref={videoRef} src="myVideo.mp4" />
      <canvas ref={canvasRef} width={640} height={360} style={{ display: 'none' }} />
      <button onClick={() => captureImage(5)}>Capture Image at 5 seconds</button>
      <button onClick={() => captureImage(10)}>Capture Image at 10 seconds</button>
      <button onClick={() => captureImage(15)}>Capture Image at 15 seconds</button>
      {capturedImages.map((image, index) => (
        <img key={index} src={image} alt={`Captured Image ${index}`} />
      ))}
    </div>
  );
}

export default VideoCapture;