使用純 JS 將 webcam的畫面,話在canvas上
context.drawImage( this.video, 0, 0, this.video.width, this.video.height );
可能有人覺得,好端端的video,為何要放在canvas上畫?
如果是要修正左右相反,或其他filter,可以用CSS就可以完成阿!
是這樣沒錯, 但最最最重要的是!!! 是要為了日後 Web也能做 抖音 來做為開端
為了讓出輸的影片或其他特殊的操作,把他放到canvas上會有更好的效果
Demo: 點我
const constraints = { //相機限制 audio: false, video: { facingMode: "user" //開前鏡頭 } }; const getFrameFromVideo = (video, canvas) => { const ctx = canvas.getContext("2d"); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.save(); //儲存狀態 ctx.translate(video.width, 0); ctx.scale(-1, 1); ctx.drawImage(video, 0, 0, video.width, video.height); ctx.restore(); //到此才輸出,才不會還沒整體操作完就放出,會造成畫面快速抖動 requestAnimationFrame(() => getFrameFromVideo(video, canvas)); }; const getCameraStream = video => { //要 camera 的權限 navigator.mediaDevices .getUserMedia(constraints) .then(function success(stream) { video.srcObject = stream; }); }; const createVideo = (id, width, height) => { const video = document.createElement("video"); video.id = id; video.width = width; video.height = height; video.autoplay = true; video.controls = true; return video; }; const createCanvas = (id, width, height) => { const canvas = document.createElement("canvas"); canvas.id = id; canvas.width = width; canvas.height = height; return canvas; }; const init = () => { const video = createVideo("vid", 480, 360); const canvas = createCanvas("canvas", 480, 360); const app = document.getElementById("app"); getCameraStream(video); getFrameFromVideo(video, canvas); app.appendChild(video); app.appendChild(canvas); console.log("init"); }; document.getElementById("app").onload = init();
@copyright MRcodingRoom
觀看更多文章請點MRcoding筆記
觀看更多文章請點MRcoding筆記