HTML5 的 getUserMedia 讓瀏覽器能直接取得攝影機畫面,再搭配 canvas 與 CSS filter,就能做出一個即時濾鏡預覽器。以下拆解三個檔案的組成。
<div class="warning">
<h2>Native web camera streaming (getUserMedia) is not supported in this browser.</h2>
</div>
<div class="container">
<h3>Current filter is: None</h3>
<button>Click here to change video filter</button>
<div style="clear:both"></div>
<div class="col">
<h2>HTML5 <video> object</h2>
<video></video>
</div>
<div class="col">
<h2>HTML5 <canvas> object</h2>
<canvas width="600" height="450"></canvas>
</div>
</div>
左邊放 video 顯示原始畫面,右邊放 canvas 顯示加工後的結果,兩者對照。
每個類別對應一種 CSS filter,並補上各瀏覽器前綴以相容舊版本:
.grayscale { filter: grayscale(1); }
.sepia { filter: sepia(0.8); }
.blur { filter: blur(3px); }
.brightness { filter: brightness(0.3); }
.contrast { filter: contrast(0.5); }
.hue-rotate { filter: hue-rotate(90deg); }
.hue-rotate2 { filter: hue-rotate(180deg); }
.hue-rotate3 { filter: hue-rotate(270deg); }
.saturate { filter: saturate(10); }
.invert { filter: invert(1); }
實作時每個規則前面都加上 -webkit-、-moz-、-o-、-ms- 前綴,最後再放無前綴的標準寫法。
document.addEventListener('DOMContentLoaded', function () {
var video = document.querySelector('video');
var canvas = document.querySelector('canvas');
var context = canvas.getContext('2d');
var audio, audioType;
var iFilter = 0;
var filters = ['grayscale', 'sepia', 'blur', 'brightness', 'contrast',
'hue-rotate', 'hue-rotate2', 'hue-rotate3', 'saturate',
'invert', 'none'];
// 相容各家前綴
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia
|| navigator.mozGetUserMedia || navigator.msGetUserMedia;
window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
if (navigator.getUserMedia) {
navigator.getUserMedia({ video: true, audio: true }, onSuccessCallback, onErrorCallback);
function onSuccessCallback(stream) {
video.src = window.URL.createObjectURL(stream) || stream;
video.play();
audio = new Audio();
audioType = getAudioType(audio);
if (audioType) {
audio.src = 'polaroid.' + audioType;
audio.play();
}
}
function onErrorCallback(e) {
var expl = 'An error occurred: [Reason: ' + e.code + ']';
console.error(expl);
alert(expl);
}
} else {
document.querySelector('.container').style.visibility = 'hidden';
document.querySelector('.warning').style.visibility = 'visible';
return;
}
// 把 video 畫面持續貼到 canvas
function drawVideoAtCanvas(obj, context) {
window.setInterval(function () {
context.drawImage(obj, 0, 0);
}, 60);
}
// canPlayType 回傳 'probably' / 'maybe' / '',不是布林值
function getAudioType(element) {
if (element.canPlayType) {
if (element.canPlayType('audio/mp4; codecs="mp4a.40.5"') !== '') { return 'aac'; }
else if (element.canPlayType('audio/ogg; codecs="vorbis"') !== '') { return 'ogg'; }
}
return false;
}
video.addEventListener('play', function () {
drawVideoAtCanvas(this, context);
}, false);
// 點擊按鈕循環切換濾鏡
document.querySelector('button').addEventListener('click', function () {
video.className = '';
canvas.className = '';
var effect = filters[iFilter++ % filters.length];
if (effect) {
video.classList.add(effect);
canvas.classList.add(effect);
document.querySelector('.container h3').innerHTML = 'Current filter is: ' + effect;
}
}, false);
}, false);
navigator.getUserMedia 存在,不支援時就把警告層顯示出來、隱藏主容器,而不是讓整頁壞掉。iFilter++ % filters.length 讓索引自動回到開頭,指標會無限輪轉,不必另外寫重置邏輯。'probably'、'maybe' 或空字串,判斷時必須比對空字串而非期待 true/false。這份程式寫於 getUserMedia 還需要加上各家前綴的年代。今天請直接使用 navigator.mediaDevices.getUserMedia(),它回傳 Promise,寫法更乾淨;同時瀏覽器要求必須在 HTTPS 或 localhost 環境下才會放行攝影機權限,這是在本機測試時最常卡住的一關。