用 javascript 把 video 變成圖片

如果要把頁面給印出來,可能會遇到 video 沒辦法看的情況,這邊我使用 js 先把 video 轉成圖片後,應該就可以避免這個情況,記錄一下這段 code。

 

$("video").each(function(){
        var video = $(this).get(0);
        var canvas = document.createElement("canvas");
        
        // set the canvas size
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        
        // get the drawing context of the canvas and add the video as an image
        // this will render the current frame inside the canvas
        canvas.getContext('2d')
            .drawImage(video, 0, 0, canvas.width, canvas.height);
 
        // create an image element
        var img = document.createElement("img");
        
        // set the image source as the base64 string representation 
        // of the content found in the canvas
        img.src = canvas.toDataURL();
        $(this).after(img)

        $(this).hide()
})