mp4等视频实现背景透明
由于工作需要,视频需要实现透明,主要是设计师不会导出透明的gif.... 所以加绿幕然后再抠视频。
视频抠图绿幕处理,视频绿幕变透明。抠什么颜色自己处理配置。代码在这一行
if (g > 200 && r < 100 && b < 100)
import { styled } from '@mui/material';
import { useEffect } from 'react';
function doLoad() {
// @ts-ignore
this.video = document.getElementById('video');
// @ts-ignore
this.c1 = document.getElementById('c1');
// @ts-ignore
this.ctx1 = this.c1.getContext('2d');
// @ts-ignore
this.c2 = document.getElementById('c2');
// @ts-ignore
this.ctx2 = this.c2.getContext('2d');
// @ts-ignore
let self = this;
// @ts-ignore
this.video.addEventListener('play', function() {
self.width = self.video.videoWidth / 2;
self.height = self.video.videoHeight / 2;
self.timerCallback();
}, false);
}
function timerCallback() {
// @ts-ignore
if (this.video.paused || this.video.ended) {
return;
}
// @ts-ignore
this.computeFrame();
// @ts-ignore
let self = this;
setTimeout(function() {
self.timerCallback();
}, 0);
}
function computeFrame() {
// @ts-ignore
this.ctx1.drawImage(this.video, 0, 0, this.width, this.height);
// @ts-ignore
let frame = this.ctx1.getImageData(0, 0, this.width, this.height);
let l = frame.data.length / 4;
for (let i = 0; i < l; i++) {
let r = frame.data[i * 4 + 0];
let g = frame.data[i * 4 + 1];
let b = frame.data[i * 4 + 2];
if (g > 200 && r < 100 && b < 100)
frame.data[i * 4 + 3] = 0;
}
// @ts-ignore
this.ctx2.putImageData(frame, 0, 0);
return;
}
var processor = {
doLoad,
timerCallback,
computeFrame,
}
export const VideoCanvas = () => {
useEffect(() => {
setTimeout(() => {
processor.doLoad()
}, 50)
}, []);
return (
<VideoCanvasWrap>
<div>
<div>
<video id="video" src="/the.mp4" controls />
</div>
<div>
<canvas id="c1" width="1137" height="555" />
</div>
<canvas id="c2" width="1137" height="555" />
</div>
</VideoCanvasWrap>
);
};
const VideoCanvasWrap = styled('div')``;