navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user' } })
.then(function (stream) {
const cameraPreview = document.getElementById('cameraPreview');
cameraPreview.srcObject = stream;
cameraStream = stream;
})
.catch(function (error) {
console.error('Error accessing the camera:', error);
});
const stopCameraButton = document.getElementById('stopCameraButton');
stopCameraButton.addEventListener('click', function () {
if (cameraStream) {
const tracks = cameraStream.getTracks();
tracks.forEach(track => track.stop());
cameraStream = null;
const cameraPreview = document.getElementById('cameraPreview');
cameraPreview.srcObject = null;
}
});
点击按钮时实现拍照逻辑,并将突破上传,代码实现
const captureButton = document.getElementById('captureButton');
captureButton.addEventListener('click', function () {
const cameraPreview = document.getElementById('cameraPreview');
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
// Set canvas dimensions to match camera preview
canvas.width = cameraPreview.videoWidth;
canvas.height = cameraPreview.videoHeight;
// Draw camera preview onto canvas
context.drawImage(cameraPreview, 0, 0, canvas.width, canvas.height);
// Convert canvas content to image data (JPEG format)
const imageDataURL = canvas.toDataURL('image/jpeg');
// Upload the image data (this is a placeholder URL)
uploadImage(imageDataURL);
});
function uploadImage(imageDataURL) {
// Here you can implement the logic to upload the image data
// to your server or cloud storage
console.log('Uploading image:', imageDataURL);
}
标签:216,canvas,const,image,cameraPreview,h5,getElementById,手机,document
From: https://blog.51cto.com/u_14816966/8433797