electron 截图,两种方式:desktopCapturer.getSources 与 navigator.mediaDevices.getUserMedia


1 // In the renderer process. 2 3 import { desktopCapturer } from 'electron'; 4 import { screen } from '@electron/remote'; 5 6 export async function captureScreen() { 7 const url_base64 = await getCaptureBySourceThumbnail(); 8 // const url_base64 = await getCaptureByStream(await getStream()); 9 return url_base64; 10 } 11 12 // 获取屏幕尺寸 13 function getSize() { 14 // scaleFactor 缩放因子 15 const { size, scaleFactor } = screen.getPrimaryDisplay(); 16 return { 17 width: size.width * scaleFactor, 18 height: size.height * scaleFactor 19 }; 20 } 21 22 // 通过 source thumbnail 获取截图 23 async function getCaptureBySourceThumbnail() { 24 if (process.platform !== 'win32') return; 25 const sources = await desktopCapturer.getSources({ 26 types: ['window', 'screen'], 27 thumbnailSize: getSize() 28 }); 29 if (!sources || !sources.length) throw new Error('sources 为空'); 30 return sources[0].thumbnail.toDataURL(); 31 } 32 33 // 获取 web RTC 视频流 34 async function getStream() { 35 const { width, height } = getSize(); 36 37 return await navigator.mediaDevices.getUserMedia({ 38 audio: false, 39 video: { 40 mandatory: { 41 chromeMediaSource: 'desktop', 42 // chromeMediaSourceId: source.id, 43 minWidth: width, // 直接设置 width、height 会报错 44 maxWidth: width, 45 minHeight: height, 46 maxHeight: height 47 } 48 } 49 }); 50 } 51 52 // 关闭视频流 53 function closeStream(stream) { 54 const tracks = stream.getTracks() || []; 55 for (const track of tracks) { 56 track.stop(); 57 } 58 } 59 60 // 通过 web RTC 视频流获取截图(存在鼠标) 61 function getCaptureByStream(stream) { 62 const { width, height } = getSize(); 63 64 return new Promise(resolve => { 65 const _video = document.createElement('video'); 66 _video.srcObject = stream; 67 _video.onloadedmetadata = () => { 68 _video.play(); 69 70 const _canvas = document.createElement('canvas'); 71 _canvas.width = width; 72 _canvas.height = height; 73 const _context = _canvas.getContext('2d'); 74 _context.drawImage(_video, 0, 0, _canvas.width, _canvas.height); 75 const url_base64 = _canvas.toDataURL('image/png'); 76 _video.pause(); 77 closeStream(stream); 78 79 return resolve(url_base64); 80 }; 81 }); 82 }

 

上一篇:不得不提的容器—JVM


下一篇:JVM基础知识[个人总结]