使用getDisplayMedia在Chrome中对元素下的所有DIV进行屏幕捕获

kx1ctssn  于 2022-12-06  发布在  Go
关注(0)|答案(1)|浏览(336)

是否有一种方法可以使用以下代码对HTML元素及其所有子元素进行截图:getDisplayMedia并将其保存/下载为单个png图像?
我不想流内容,我只是有一个非常复杂的SVG/Canvas/HTML设置,需要采取整个根DIV的截图。尝试了许多技术的图像快照在Chrome中,但没有一个做的伎俩,捕捉一切,所以我想也许MediaRecorder〉png将工作?
谢谢你

igetnqfo

igetnqfo1#

如果你的元素完全适合视口,我推荐最近登陆Chrome的区域捕捉API。
有关详细信息,请参阅https://developer.chrome.com/docs/web-platform/region-capture/

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 */

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;
}

将来,您可能会使用元素捕获Web API。请参阅当前的建议:https://github.com/WICG/proposals/issues/73

相关问题