Capture Photos with WebRTC and Vue: A Step‑By‑Step Front‑End Tutorial

This tutorial shows how to request camera access, display the video stream, and capture a snapshot onto a canvas using WebRTC and Vue, complete with live demo links, illustrative images, and full source code for index.html and main.js.

Open Source Tech Hub
Open Source Tech Hub
Open Source Tech Hub
Capture Photos with WebRTC and Vue: A Step‑By‑Step Front‑End Tutorial

Online Demo

Live demonstration is available at https://webrtc.tinywan.com/docs-2022/demo-03/index.html.

Camera Permission

When the page loads it requests access to the user's camera via navigator.mediaDevices.getUserMedia. The user must grant permission for the video stream to be displayed.

Camera permission illustration
Camera permission illustration

Photo Capture

After the video stream is shown, clicking the “拍照” (Take Photo) button draws the current video frame onto a canvas, effectively taking a snapshot.

Screenshot of captured photo
Screenshot of captured photo

Source Code

The HTML file ( index.html) sets up a <video> element, a button, and a <canvas> element, and loads Vue 3 from a CDN and the script main.js.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>WebRTC实战教程:如何使用摄像头拍照</title>
  </head>
  <body>
    <h1>WebRTC实战教程:如何使用摄像头拍照</h1>
    <div id="app">
      <div>
        <video ref="video" autoplay width="400" height="300"></video>
      </div>
      <div>
        <button @click="btnTakePhotoClicked">拍照</button>
      </div>
      <div>
        <canvas ref="canvas" width="400" height="300"></canvas>
      </div>
    </div>
    <script src="https://cdn.staticfile.org/vue/3.0.5/vue.global.js"></script>
    <script src="main.js"></script>
  </body>
</html>

The JavaScript ( main.js) creates a Vue app that:

Initializes the video stream in _initDevice using

navigator.mediaDevices.getUserMedia({video:true, audio:false})

and stores the 2‑D canvas context.

Provides btnTakePhotoClicked which draws the current video frame onto the canvas with this._context2d.drawImage(this.$refs.video, 0, 0, 400, 300).

Finally, the app is mounted to the element with id #app.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

VueCameraWebRTCPhoto Capture
Open Source Tech Hub
Written by

Open Source Tech Hub

Sharing cutting-edge internet technologies and practical AI resources.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.