可以使用 canvas
元素來截取視頻某一幀并生成封面。
首先,在 video
?標簽上設(shè)置視頻源地址和自動播放屬性:
<video src="video.mp4" autoplay></video>
然后,在 canvas
?標簽上定義寬高和樣式,并通過 JavaScript 獲取視頻元素和 canvas 元素:
<canvas width="640" height="360" style="display:none;"></canvas>
<script>
const video = document.querySelector('video');
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
</script>
接著,定義一個函數(shù)來截取視頻某一幀,并將其渲染到 canvas 上:
<script>
function captureFrame() {
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
}
</script>
在需要生成封面的地方調(diào)用該函數(shù)即可:
<button onclick="captureFrame()">生成封面</button>
最后,將 canvas 元素轉(zhuǎn)換為圖片元素并插入到頁面中:文章來源:http://www.zghlxwxcb.cn/news/detail-766048.html
<script>
function captureFrame() {
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
const dataURL = canvas.toDataURL();
const img = document.createElement('img');
img.src = dataURL;
document.body.appendChild(img);
}
</script>
完整代碼如下:文章來源地址http://www.zghlxwxcb.cn/news/detail-766048.html
<video src="video.mp4" autoplay></video>
<canvas width="640" height="360" style="display:none;"></canvas>
<button onclick="captureFrame()">生成封面</button>
<script>
const video = document.querySelector('video');
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
function captureFrame() {
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
const dataURL = canvas.toDataURL();
const img = document.createElement('img');
img.src = dataURL;
document.body.appendChild(img);
}
</script>
到了這里,關(guān)于js截取video視頻某一幀做封面的簡單案例的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!