Real-Time Photo Capture with Text Watermark Using PHP and JavaScript
This tutorial explains how to access a webcam with JavaScript, display the live video in a web page, capture a frame onto a canvas, overlay custom text as a watermark, and export the result as a data URL for further processing.
Camera devices are common in daily life, and with modern web technologies it is possible to capture photos in real time and add text watermarks using PHP as the backend and JavaScript on the front end. This article walks through the complete implementation.
First, ensure a webcam is connected and the PHP environment is set up. The page uses a video element to stream the live camera feed.
<!DOCTYPE html>
<html>
<head>
<title>实时拍摄照片并加入文字水印</title>
<style>
#video { width: 100%; height: auto; }
#canvas { display: none; }
</style>
</head>
<body>
<video id="video" autoplay></video>
<canvas id="canvas"></canvas>
<script>
navigator.mediaDevices.getUserMedia({ video: true })
.then(function(stream) {
var video = document.getElementById('video');
video.srcObject = stream;
video.play();
})
.catch(function(err) {
console.error("无法获取摄像头的画面: ", err);
});
</script>
</body>
</html>The getUserMedia API obtains the live video stream and feeds it into the video tag. After this setup, the next step is to capture a frame and add a text watermark.
We use a canvas element to draw the current video frame and then overlay the watermark text.
<script>
var video = document.getElementById('video');
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
document.addEventListener('DOMContentLoaded', function() {
var button = document.createElement('button');
button.textContent = '拍摄照片';
button.addEventListener('click', function() {
context.drawImage(video, 0, 0, canvas.width, canvas.height);
context.font = 'bold 20px Arial';
context.fillStyle = 'white';
context.fillText('水印文字', 10, 40);
var dataURL = canvas.toDataURL('image/png');
// In this place you can send the dataURL to the server for saving or other operations
});
document.body.appendChild(button);
});
</script>When the page loads, a button is created; clicking it draws the video frame onto the canvas, applies the watermark using fillText , and converts the canvas content to a data URL with toDataURL . This data URL can then be transmitted to a server or saved locally.
By following these steps, you have a functional solution for real‑time photo capture with a text watermark using PHP‑backed web pages, and you can further customize the watermark style or store the images as needed.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
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.