上一篇尝试了 WebRTC 的切换设备并显示自己的影像,今天我们将通过上一次的程序码来做拍照的功能并且加上一些滤镜处理,我们将实作:
在视讯中取得画面截图
将图片保存下来
在图片上加上滤镜
复制上一次的程序码
❯ cd WebRTC/sample
❯ cp -r input-output take-a-photo
在 index.html video
标签下增加
...
<div><button id="shoot">拍照</button></div>
...
main.js 中增加截图的方法,传入参数为 video 也就是显示视讯的那个元件,方法内会产生一个canvas,并将 video 的画面绘制在上面并回传
function capture(video) {
const w = video.videoWidth
const h = video.videoHeight
const canvas = document.createElement('canvas')
canvas.width = w
canvas.height = h
canvas.getContext('2d').drawImage(video, 0, 0, w, h)
return canvas
}
main.js 中增加下载的方法,传入url,方法内会产生一个 a 标签,将要下载的内容写入,并且点击下载,最後把标签删除
function download(url) {
var a = document.createElement('a')
a.download = 'Image.jpg'
a.href = url
document.body.appendChild(a)
a.click()
a.remove()
}
把拍照的按钮与下载功能绑定
document.querySelector('button#shoot').onclick = () =>
download(capture(videoElement).toDataURL('image/jpeg'))
加上滤镜,在 index.html header 中加入 css ,以及一个选择器。
https://developer.mozilla.org/zh-CN/docs/Web/CSS/filter
<head>
...
<style>
.none {
-webkit-filter: none;
filter: none;
}
.blur {
-webkit-filter: blur(2px);
filter: blur(2px);
}
.grayscale {
-webkit-filter: grayscale(1);
filter: grayscale(1);
}
.invert {
-webkit-filter: invert(1);
filter: invert(1);
}
.sepia {
-webkit-filter: sepia(1);
filter: sepia(1);
}
</style>
</head>
<body>
...
<div>
<label>滤镜:</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="sepia">Sepia</option>
</select>
</div>
...
</body>
在 main.js 中,加入滤镜绑定
const filtersSelect = document.querySelector('select#filter')
filtersSelect.onchange = () => {
videoElement.className = filtersSelect.value
}
打开终端机 cd 到资料夹内并输入 http-server
,使用浏览器开启 http://localhost:8080
就可以查看效果了。
* http-server 安装
<<: 从 JavaScript 角度学 Python(25) - 例外处理
>>: [Day11] Storybook - Controls
看到这里,你可能还是很疑惑,到底 vim 好用在哪?嘿嘿,那是因为强大的外挂还没装啦!网路上会有一些...
现在我们有一个可以输入日志的介面了,但日志就是每天都要写的意思,只有一篇怎麽够呢?我们来加上blog...
这两天大家好像都在绑定数位五倍券和抢银行优惠,还有登记一些抽签的加码券,结果造成系统大当机。威尔猪...
今天要来讲解如何在 TypeScript (TS) 修改成员, 以我们之前的类别为例, let em...
上一篇我们讲解怎麽产生目标 parser 的 parse 方法,这篇来讲解 generator 的内...