提示💡

drawImage、toDataURL

function manualCapture() {
	const video = document.getElementById("myVideo");
	const canvas = document.createElement("canvas");
	var ctx = canvas.getContext("2d");
	const ratio = window.devicePixelRatio || 1;
	ctx.scale(ratio, ratio);
	canvas.width = video.offsetWidth * ratio;
	canvas.height = video.offsetHeight * ratio;
	ctx.drawImage(video, 0, 0, canvas.width, canvas.height);// 在画布上绘制图像
	const img = document.getElementById("image");
	console.log("图片地址", canvas.toDataURL("image/jpg"));
	img.src = canvas.toDataURL("image/jpg"); // 生成图片地址
}

播放器截图

// 截图
const captureScreen = async (el, size) => {
  if (!el) return;
  let canvas = document.createElement('canvas');
  let { width, height } = size;
  if (!width || !height) {
    const { width: defaultWidth, height: defaultHeight } = el.getBoundingClientRect();
    width = defaultWidth;
    height = defaultHeight;
  }
  canvas.width = width;
  canvas.height = height;
  let ctx = canvas.getContext('2d');
  ctx.drawImage(el, 0, 0, width, height);
  const url = canvas.toDataURL('image/jpeg');
  const file = await _canvasToBlob(canvas);
  return { url, file };
};
const _canvasToBlob = (canvas) => {
  return new Promise((resolve, reject) => {
    try {
      canvas.toBlob((blob) => {
        resolve(blob);
      });
    } catch (error) {
      reject(error);
    }
  });
};	

常见问题

渲染图片跨域问题: 使用 crossorigin="anonymous" 解决

错误

Screenshot.html:55 Uncaught DOMException: Failed to execute ‘toDataURL’ on ‘HTMLCanvasElement’: Tainted canvases may not be exported.

扩展阅读