ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2021-06-26 17:32:45  阅读:169  来源: 互联网

标签:getSources mediaDevices canvas const desktopCapturer height width video return



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 }

 

标签:getSources,mediaDevices,canvas,const,desktopCapturer,height,width,video,return
来源: https://www.cnblogs.com/M1n90/p/14934833.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有