最近在弄p5js ,一个在html5里面嵌入processing的js小框架。canvas绘画啊,这是一个不得不说的问题,涉及到html5的视频捕获原理。
以为p5js是和processing一样的视频像素数组存储机制,研究完才发现并不是这样的。Processing里的像素数组里面的每一个元素包涵了RGB信息。但p5js直接把RGBA放在了像素数组里,也就是说P5js的像素数组长度是原来的4倍,所以想获取到P5js的视频流像素数组,写法和在Processing里还不一样,详细的可以参考我的代码。以及一些参考信息。
我把P5js获取视频流的Project小demo放到了自己的服务器上,感兴趣的可以自己打开看。http://www.liziyang.com/p5video/。另外,只能使用win下的chrome浏览器观看。
代码:
//http://p5js.org/reference/#/p5/pixels[]
//http://p5js.org/reference/#/p5/windowWidth
//http://p5js.org/reference/#/p5/fullscreen
//http://p5js.org/examples/dom-video-pixels.html
//http://p5js.org/reference/#/p5/push
var capture;
var camWidth, camHeight;
var pd = 10; // pixel Density
var widthsize;
var heightsize;
function setup() {
createCanvas(windowWidth, windowHeight);
frameRate(30);
capture = createCapture(VIDEO); // feed
capture.size(640, 480);
capture.hide();
// Assuming a 640 * 480 pixels camera
camWidth = 640;
camHeight = 480;
widthsize = windowWidth/640;
heightsize = windowHeight/480;
}
function draw() {
//background(0);
drawAllPixels();
}
function drawAllPixels() {
var x, y;
capture.loadPixels();
// Divide by 2 and multiply index by 8 is to reduce the final resolution
for (y = 0; y < camHeight; y+=pd) {
for (x = 0; x < camWidth; x+=pd) {
var idx = 4 * (y * camWidth + x);
push();
translate(windowWidth-x*widthsize-pd*widthsize, y*heightsize);
rotate(radians(capture.pixels[idx]));
noStroke();
fill(capture.pixels[idx],capture.pixels[idx+1],capture.pixels[idx+2],capture.pixels[idx+3]);
rect(0,0,pd*widthsize+30,pd*heightsize+30);
//noFill();
//stroke(0);
//ellipse(0,0,pd*widthsize-2,pd*heightsize-2);
pop();
}
}
fill(255);
textSize(72);
textFont("Arial");
text("Hello World!", windowWidth/2-180, 90);
}