HTML5美顏拍照效果代碼實現了許多驚人的功能,如切換照相機和視頻源,拍照和錄像,以及在圖像上應用各種濾鏡
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>HTML5 Camera</title> </head> <body> <div> <h1>美顏攝像頭</h1> <video id="video" width="640" height="480" autoplay></video> <br/> <button id="snap">拍照</button> <canvas id="canvas" width="640" height="480"></canvas> </div> <script> 'use strict'; const video = document.getElementById('video'); const canvas = document.getElementById('canvas'); const snapBtn = document.getElementById('snap'); var imageSource; // 獲取視頻流 navigator.mediaDevices.getUserMedia({ audio: false, video: true }) .then(function(stream) { video.srcObject = stream; video.play(); }) .catch(function(err) { console.log("訪問攝像頭錯誤:" + err); }); // 拍照 snapBtn.addEventListener('click', function() { var context = canvas.getContext('2d'); context.drawImage(video, 0, 0, canvas.width, canvas.height); imageSource = canvas.toDataURL(); // 獲取圖像數據URL }); </script> </body> </html>
在上述代碼中,我們使用了canvas來截取攝像頭的視頻流以及應用各種特效,同時使用了getUserMedia()函數來獲得攝像頭的數據流。在拍照后,我們可以從canvas元素中獲取圖像數據并將其作為一個數據URL存儲在imageSource變量
下一篇html5網頁轉向代碼