Is there a way to take a screenshot of a HTML element and all its children using: getDisplayMedia and save it / download it as a single png image?
I do not want to stream content, I just have a very complex SVG / Canvas / HTML setup and need to take a screenshot of the entire root DIV. Tried many of the techniques for image snapshot in Chrome but non of them did the trick in capturing everything, so I am thinking maybe MediaRecorder > png will work?
thanks you
If your element fits entirely in the viewport, I'd recommend the recent Region Capture API that landed in Chrome.
See https://developer.chrome.com/docs/web-platform/region-capture/ for more details.
const mainContentArea = document.querySelector("#mainContentArea");
const cropTarget = await CropTarget.fromElement(mainContentArea);
// Prompt user to share the tab's content.
const stream = await navigator.mediaDevices.getDisplayMedia({ preferCurrentTab: true });
const [track] = stream.getVideoTracks();
// Start cropping the self-capture video track using the CropTarget <-- Magic!
await track.cropTo(cropTarget);
const canvas = drawToCanvas(stream);
canvas.toBlob((blob) => {
// See https://web.dev/patterns/files/save-a-file/ to save this blob locally.
});
/* Utils */
async function drawToCanvas(stream) {
const canvas = document.createElement("canvas");
const video = document.createElement("video");
video.srcObject = stream;
// Play it.
await video.play();
// Draw one video frame to canvas.
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext("2d").drawImage(video, 0, 0);
return canvas;
}
In the future, you may be able to use the Element Capture Web API. See the current proposal: https://github.com/WICG/proposals/issues/73
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With