接下來會展示簡單實作並搭配CSS filter屬性,
注意: 這邊一樣利用Google包裝好的shim lib - adapter.js.來方便我們操作。
<!-- index.html -->
<video autoplay></video>
加上兩個Button,Capture按鈕負責重新啟用mediaStream,Stop按紐負責停止功能
引入adapter.js幫我們處理好相容性問題,方便主程式操作getUserMedia。
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
<!-- 主要程式 -->
<script src="./js/main.js"></script>
// ./js/main.js
const video = document.querySelector('video');
const constraints = {
audio: false,
video: true
};
function handleSuccess(stream) {
window.stream = stream; // 方便可以在瀏覽器console
video.srcObject = stream;
}
function handleError(error) {
console.log('navigator.MediaDevices.getUserMedia error: ', error.message, error.name);
}
navigator.mediaDevices.getUserMedia(constraints).then(handleSuccess).catch(handleError);
利用CSS filter屬性 來操作Video Element,看看效果如何
這次的index.html
將會新增如下:
<div id="screenshot">
<!-- ... -->
<label for="filter">CSS Filter: </label>
<select id="filter">
<option value="none">None</option>
<option value="blur">Blur</option>
<option value="grayscale">Grayscale</option>
<option value="invert">Invert</option>
<option value="contrast">Contrast</option>
<option value="sepia">Sepia</option>
<option value="opacity">Opacity 50%</option>
<option value="saturate">Saturate</option>
<option value="hue-rotate">Hue Rotate</option>
<option value="drop-shadow">Drop Shadow</option>
</select>
<!-- ... -->
</div>
<!-- ... -->
列出大部分的filter屬性,來進行嘗試
class name對應以下css style:
.none {
filter: none;
}
.blur {
filter: blur(3px);
}
.grayscale {
filter: grayscale(1);
}
.invert {
filter: invert(1);
}
.contrast {
filter: contrast(200%);
}
.sepia {
filter: sepia(1);
}
.opacity {
filter: opacity(50%);
}
.saturate {
filter: saturate(200%);
}
.hue-rotate {
filter: hue-rotate(180deg);
}
.drop-shadow {
filter: drop-shadow(16px 16px 10px black);
}
改寫一下主程式:
// ./js/main.js
// ....
const screenshotButton = document.querySelector("#screenshot-button");
const filterSelector = document.querySelector("#filter");
const video = document.querySelector("#screenshot video");
const canvas = document.querySelector("canvas");
screenshotButton.onclick = video.onclick = function () {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.className = filterSelector.value;
canvas.getContext("2d").drawImage(video, 0, 0, canvas.width, canvas.height);
};
filterSelector.onchange = function () {
video.className = filterSelector.value;
}
// ....
試試看,畫面上的影像會出現怎樣的變化~
本章節了解到:
這次主要是video的應用居多,
但另外audio其實也有許多應用,等著大家去探索嘗試。
這邊列出幾個:
新手入門,如有錯誤,歡迎指正~~~
系列文章同步更新於部落格