我想使用p5.js库进行视频处理。但是当通过 select()功能使用外部视频元素时,自己的代码不起作用。 但是当使用 createCapture()函数代替 select()
时,代码可以正常工作//index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="assets/vendor/jquery-3.0.0.min.js"></script>
<script src="assets/vendor/p5/p5.min.js"></script>
<script src="assets/vendor/p5/p5.dom.min.js"></script>
<script src="assets/vendor/p5/p5.sound.min.js"></script>
<script src="assets/scripts/script.js"></script>
</head>
<body>
<div class="snapshot">
<video id="video" autoplay=""></video>
</div>
</body>
</html>
//script.js
$(document).ready(e => {
window.currentEffect = 0;
let v = $("#video");
effects = [{
name: "Normal",
effect: (p) => {
let v;
p.preload = () => {};
p.setup = () => {
v = p.select("#video");
if (p.select("#canvas") === null) p.createCanvas(v.width, v.height).id("#canvas");
else {
p.select("#canvas").remove();
p.createCanvas(v.width, v.height).id("#canvas");
}
p.pixelDensity(1);
};
p.draw = () => {
p.background(51);
p.translate(p.width, 0);
p.scale(-1, 1);
p.loadPixels();
for (let y = 0; y < p.height; y++) {
for (let x = 0; x < p.width; x++) {
let i = (x + y * p.width) * 4,
r = v.pixels[i + 0],
g = v.pixels[i + 1],
b = v.pixels[i + 2],
rb = (r + g + b) / 3;
p.pixels[i + 0] = rb;
p.pixels[i + 1] = rb;
p.pixels[i + 2] = rb;
p.pixels[i + 3] = 255;
}
}
p.updatePixels();
};
}
}];
navigator.mediaDevices.getUserMedia({
audio: false,
video: {
mandatory: {
minWidth: v.width(),
minHeight: v.height(),
maxWidth: v.width(),
maxHeight: v.height()
}
}
})
.then(stream => {
v.attr({
"src": window.URL.createObjectURL(stream),
"autoplay": "true"
});
})
.catch(err => {
console.error(err);
});
new p5(effects[0].effect);
});