Skip to content

Checking your reading list…

Retry verification

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

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

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.

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.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

VueCameraWebRTCPhoto Capture

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion