上傳影片,取第一幀,縮圖demo

国服第一李师师發表於2024-11-28
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #img-content {
            display: flex;
            padding:10px;
            border:5px solid red;
        }
        img {
            width:100px;
            height:100px;
            margin-right:20px;
        }
    </style>
</head>
<body>
    <input type="file" />
    <div id="img-content"></div>
    <script>
        const inp = document.querySelector('input[type=file]')
        inp.onchange = function (e) {
            const file = e.target.files[0]
            console.log(file)
            const content = document.getElementById('img-content')
            for(let i=0;i<10;i++){
                captureFrame(file,i).then(({url})=>{
                    console.log(url)
                    const img = document.createElement('img')
                    img.src = url
                    content.appendChild(img)
                })
            }
            
        }
        function captureFrame(file,time=0) {
            return new Promise((resolve) => {
                const video = document.createElement('video')
                video.currentTime = time
                video.muted = true
                video.autoplay = true
                video.src = URL.createObjectURL(file)
                video.oncanplay = function () {
                    const canvas = document.createElement('canvas')
                    canvas.width = video.videoWidth
                    canvas.height = video.videoHeight
                    const ctx = canvas.getContext('2d')
                    ctx.drawImage(video,0,0,canvas.width,canvas.height)
                    // document.body.appendChild(canvas)
                    canvas.toBlob((blob)=>{
                        const url = URL.createObjectURL(blob)
                        console.log(url)
                        resolve({url,blob})
                    })
                }
            })
        }

    </script>
</body>
</html>

  

相關文章