编程技术文章分享与教程

网站首页 > 技术文章 正文

js 录屏截图

hmc789 2024-11-21 15:50:11 技术文章 2 ℃

<video id="video" style="height: 400px;width: 400px;" autoplay></video>

<button id="start">开始</button>

<button id="stop">停止</button>

<script>

// js

const displayMediaOptions = { // 参数的详情可以在mdn网站查找

video: {

cursor: "always"

},

audio: false

};

let videoElem = document.getElementById("video");

document.getElementById("start").addEventListener('click', function () {

startCapture()

})

document.getElementById("stop").addEventListener('click', function () {

stopCapture()

})

async function startCapture() {

try {

videoElem.srcObject = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);

videoElem.addEventListener("loadedmetadata", function () {

canvas.width = videoElem.videoWidth;

canvas.height = videoElem.videoHeight;

});

videoElem.addEventListener("timeupdate", function () {

try {

const currentTime = parseFloat(videoElem.currentTime);

if (currentTime >= 2) {

stopCapture()

}

} catch (err) {

console.log("video has deleted: " + err);

}

});

videoElem.play();

} catch (err) {

console.error("Error: " + err);

}

}

function stopCapture(evt) {

let ctx = canvas.getContext("2d");

ctx.drawImage(videoElem, 0, 0, videoElem.videoWidth, videoElem.videoHeight);

//拿到一个dataUrl,可new Image(),然后图片的对象的src设置为url,就可以得到图片dom元素

let imgURL = canvas.toDataURL("image/jpeg");

console.log(imgURL)

let tracks = videoElem.srcObject.getTracks();

tracks.forEach(track => track.stop());

videoElem.srcObject = null;

}

</script>

Tags:

标签列表
最新留言