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.
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.
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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Tech Hub
Sharing cutting-edge internet technologies and practical AI resources.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
