Demonstrates how to access camera pixel data and draw it with reduced resolution like pixel art.
p5.js 2.0
Camera Pixel Data
View Source Code
let video;
let paramInput, paramValue;
async function setup() {
createCanvas(windowWidth, windowHeight);
pixelDensity(1);
video = await createCapture(VIDEO);
video.size(640, 480);
video.hide();
paramInput = select("#paramInput");
paramValue = select("#paramValue");
}
function draw() {
background(20);
if (
!video ||
!video.elt ||
video.elt.readyState < 2 ||
video.elt.videoWidth === 0
) {
fill(255);
textAlign(CENTER, CENTER);
textSize(24);
text("Loading camera...", width / 2, height / 2);
return;
}
if (paramInput && paramValue) {
let step = int(paramInput.value());
paramValue.html(step);
let img = video.get();
img.loadPixels();
if (img.pixels && img.pixels.length > 0) {
let w = img.width;
let h = img.height;
let aspect = w / h;
let drawW = height * aspect;
let drawH = height;
if (drawW > width) {
drawW = width;
drawH = width / aspect;
}
let drawX = (width - drawW) / 2;
let drawY = (height - drawH) / 2;
noStroke();
push();
translate(width, 0);
scale(-1, 1); // mirror
let invDrawX = width - (drawX + drawW);
for (let y = 0; y < h; y += step) {
for (let x = 0; x < w; x += step) {
let index = (y * w + x) * 4;
let r = img.pixels[index];
let g = img.pixels[index + 1];
let b = img.pixels[index + 2];
fill(r, g, b);
let px = map(x, 0, w, invDrawX, invDrawX + drawW);
let py = map(y, 0, h, drawY, drawY + drawH);
let pw = drawW / (w / step);
let ph = drawH / (h / step);
rect(px, py, pw, ph);
}
}
pop();
}
}
}
function windowResized() {
resizeCanvas(windowWidth, windowHeight);
}