Bootstrap

js视频播放截图并下载-react hook

使用canvas进行视频播放过程图片的绘制和下载。

import React, { useEffect } from 'react';
import './App.css';

import test_video from './assets/yasuo.MP4'

function App() {

  useEffect( () => {

  })

  const capture = () => {
    // 获取video标签
    let video = document.querySelector('#show');
    video.setAttribute('crossOrigin', 'anonymous')

    // 获取canvas标签
    var canvas = document.getElementById('canvas');

    //获取绘图环境
    var cobj = canvas.getContext('2d'); 

    // 绘制图片
    cobj.drawImage(video, 0, 0,200, 300);

    // 获取截图得base64格式文件
    let base64 = canvas.toDataURL()
    // console.log(base64)
    
    // 时间戳
    let name = new Date(+new Date() + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/,'').replace(/-|:|\s/g, '-')
    
    // 下载图片
    dowImage(base64, name)
  }

  // a标签下载图片
  const dowImage = (url, name) => {
    fetch(url).then(res => res.blob()).then(blob => {
        var a = document.createElement('a');
        var url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = name;
        a.click();
        window.URL.revokeObjectURL(url);
    })
  }

  return (
    <div className="App">
      <button onClick = {capture}>截图</button>

      <video id='show' controls>
        <source src={test_video}></source>
      </video>

      <canvas id="canvas" width = "200" height = "300" ></canvas>
    
  
    </div>
  )
}


export default App;

效果展示

;