想讓使用者把影片中的某一幀存成圖片?HTML5 的 canvas 加上 drawImage() 就能完成,整個流程只需要幾行程式碼。
<video id="video" controls="controls">
<source src=".mp4" />
</video>
<button id="capture">Capture</button>
<div id="output"</div>
(function () {
"use strict";
var video, $output;
var scale = 0.25;
var initialize = function () {
$output = $("#output");
video = $("#video").get(0);
$("#capture").click(captureImage);
};
var captureImage = function () {
var canvas = document.createElement("canvas");
canvas.width = video.videoWidth * scale;
canvas.height = video.videoHeight * scale;
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
var img = document.createElement("img");
img.src = canvas.toDataURL();
$output.prepend(img);
};
$(initialize);
}());
document.createElement 動態產生一塊畫布,不需要寫在 HTML 裡。videoWidth / videoHeight 為基準,乘上 scale 縮放比例。範例用 0.25 輸出四分之一大小的縮圖,改成 1 就是原始解析度。drawImage(video, 0, 0, w, h) 會把「當前這一幀」貼到畫布上,所以按下按鈕的瞬間就是截圖的時間點。canvas.toDataURL() 輸出 base64 資料 URL,直接指定給 img.src 即可顯示。prepend 把新圖片放到輸出區最前面,連續截圖時最新的會排在最上面。toDataURL() 時瀏覽器會丟出安全性錯誤。readyState 已達可用狀態,否則 videoWidth 可能是 0。toDataURL('image/png') 的結果放進 <a download> 的 href 觸發下載。