<video id="video" oncanplay="init()" loop src="./2.mp4" width="400"></video>
<canvas id="cvs"></canvas>
<canvas id="cvs2" onclick="video.play()" ></canvas>
css部分代码
body {
display: flex;
}
video,
canvas {
border: 2px solid black;
}
js代码
const init = () => {
const ctx = cvs.getContext('2d')
const ctx2 = cvs2.getContext('2d')
//把视频的宽高赋值给cvs 和cvs2
cvs.height = cvs2.height = video.offsetHeight
cvs.width = cvs2.width = video.offsetWidth
// 定义一个函数
const playVideo = () => {
requestAnimationFrame(playVideo)
const { width, height } = cvs
// 把video复刻到cvs1中
ctx.drawImage(video, 0, 0, width, height)
const data = ctx.getImageData(0, 0, width, height).data
//每次渲染之前 先要把cav2清空一下
ctx2.clearRect(0, 0, width, height)
// 定义一个稀释比例
const bl = 8
ctx2.font = '12px serif'
/**
* +=4 是因为RGBA是有四个 所以要设置成为4个
*/
for (let i = 0; i < data.length; i += 4 * bl) {
const x = parseInt((i + 1) % (width * 4) / 4)
const y = parseInt(i / (width * 4))
if (x % bl === 0 && y % bl === 0) {
// 转灰度图 从网上抄的
const g = parseInt((data[i] + data[i + 1] + data[i + 2]) / 3.3)
ctx2.fillStyle = `rgba(${g},${g},${g},${data[i + 3]})`
ctx2.fillText('8',x,y)
}
}
}
playVideo()
}