天天看點

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;

           
js視訊播放截圖并下載下傳-react hook

繼續閱讀