xxxxxxxxxx
100
// live software mirror
// demo code for arts 444, sp 2019
// code by grosser, march 2019
// NOTE: make sure your index.html file is referencing
// p5.js version 0.7.1 (same for DOM and sound)
// try on your mobile phone w/ present mode
// (text yourself the URL)
let cam;
let xScale;
let yScale;
let showCamera = false;
function setup() {
createCanvas(windowWidth, windowHeight);
pixelDensity(displayDensity());
rectMode(CENTER);
noStroke();
//frameRate(1);
// setup webcam for capture
cam = createCapture(VIDEO); // create capture obj
cam.size(40, 30); // use low res input for speed
cam.hide(); // hide default cam stream display
// this enables us to change cam input size easily
xScale = width / cam.width;
yScale = height / cam.height;
}
function draw() {
// this allows you to toggle a live view on/off
if (showCamera) cam.show();
else cam.hide();
// before you can access the pixels array of the camera
// you have to "load" the pixels
cam.loadPixels();
// this nested for() runs through all camera pixels
// in x/y and grabs the rgb data from each pixel
// then uses that info to draw a rect back to screen
for (let y = 0; y < cam.height; y++) {
// note that we're running x backwards (so we can
// flip image like a real mirror does)
for (let x = cam.width; x >= 0; x--) {
// formula for accessing r/g/b from array
// (they are stored sequentially)
let index = (x + y * cam.width) * 4;
let r = cam.pixels[index + 200];
let g = cam.pixels[index + 1];
let b = cam.pixels[index + 2];
// make sure cam data is flowing...
if (r != undefined) {
// fill rect w/ color from camera
fill(r, g, b, 128);
// draw rect at cam.width-x-1 to finish the image flip
// here I'm also scaling and adding some random
rect(
((cam.width - x - 1) * xScale) + xScale / 2 + random(4),
(y * yScale) + yScale / 2 + random(4),
// mouseX, //eliminates xScale limit on rect width
// y //eliminates yScale limit on rect width
map(mouseX, 0, width, 100, xScale + 200),
map(mouseY, 0, height, 1, yScale + 2)
//see map() in p5js reference for info on map()
);
// rect(
// (x * xScale) + xScale / 2 + random(4),
// (y * yScale) + yScale / 2 + random(4),
// mouseX, //eliminates xScale limit on rect width
// mouseY //eliminates yScale limit on rect width
// );
} // end if
} // end x for()
} // end y for()
// when done accessing pixel array for camera, call
// updatePixels to let p5 know you're done
cam.updatePixels();
}
// define these so we can return false
// this makes it so dragging on mobile doesn't try to
// scroll but instead gets interpreted as mouse movements
function touchStarted() { return false; }
function touchEnded() { return false; }