Vue: How to Share Your Screen

Document: https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia

Method: https://developer.mozilla.org/en-US/docs/Web/API/Screen_Capture_API/Using_Screen_Capture

Example Codes:

<template>

  <video ref="video" autoplay="true" style="width: 500px; height: 300px"></video>
  <canvas ref="canvas" style="display: none"></canvas>

</template>
 


<script lang="ts" setup>


 import { onMounted, ref } from 'vue'

  const canvas = ref()
  const video = ref()
  const timer = ref()
 



 onMounted(async () => {
let stream = null
try {
    stream = await navigator.mediaDevices.getDisplayMedia({
        video: true,
        audio: true
    })
    video.value.srcObject = stream
    dumpOptionsInfo()
    const ctx = canvas.value.getContext('2d')
    // devicePixelRatio returns the ratio of the physical pixel resolution of the current display device to the CSS pixel resolution, allowing for better reproduction of realistic video scenes
    const ratio = window.devicePixelRatio || 1
    ctx.scale(ratio, ratio)
    // The canvas size remains the same as the image size, and the screenshot is not redundant
    canvas.value.width = video.value.offsetWidth * ratio
    canvas.value.height = video.value.offsetHeight * ratio
    timer.value = setInterval(() = > {
        ctx.drawImage(video.value, 0, 0, canvas.value.width, canvas.value.height)
        const imgUrl = canvas.value.toDataURL('image/jpeg')
        console.log('imgUrl: ', imgUrl)
    }, 5000)
} catch (e) {
    console.log(e)
}
// Monitor to manually turn off screen sharing
const videoTrack = video.value.srcObject.getVideoTracks()[0]
videoTrack.addEventListener('ended', handleStop)
  })

const dumpOptionsInfo = () = > {
    const videoTrack = video.value.srcObject.getVideoTracks()[0]
    console.info('Track settings:')
    console.info(JSON.stringify(videoTrack.getSettings(), null, 2))
    console.info('Track constraints:')
    console.info(JSON.stringify(videoTrack.getConstraints(), null, 2))
}
const handleStop = () = > {
    clearInterval(timer.value)
    let tracks = video.value.srcObject.getTracks()
    tracks.forEach((track: {
        stop: () = > any
    }) = > track.stop())
    video.value.srcObject = null
}

 

Read More:

Leave a Reply

Your email address will not be published. Required fields are marked *