xxxxxxxxxx
85
// based on the tutorial from the reference here:
// https://p5js.org/reference/#/p5/createCapture
let capture;
// nice concise function from Andrew Tatomyr
// https://stackoverflow.com/users/6858966/andrew-tatomyr
// taken from here
// https://stackoverflow.com/questions/17428587/transposing-a-2d-array-in-javascript
function transpose(matrix) {
return matrix.reduce((prev, next) => next.map((item, i) => (prev[i] || []).concat(next[i])), []);
}
// sum and mean copied from array-toolkit library on npm
// https://www.npmjs.com/package/array-toolkit
function sum(inputArray) {
return inputArray.reduce((acc, cur) => {
return acc + cur;
}, 0);
}
function mean(inputArray) {
return sum(inputArray) / inputArray.length;
}
function processArray (frames, input) {
frames.shift();
frames.push(input);
return frames
}
function buildArray (n, fillFunction) {
let outputArray = [];
for (let i = 0; i < n; i++) {
outputArray.push(fillFunction(i))
}
return outputArray
}
// this is the core data structure that will allow us to reduce jitter
// change the value of n for buildArray (20) to other values to increase or reduce sensitivity
// higher values will make it less sensitive
let pixelValues = buildArray(20, i => [0,0,0,0]);
function setup() {
createCanvas(800, 800);
// Create the video capture and hide the element.
capture = createCapture(VIDEO);
capture.hide();
describe("a video stream from the webcam");
}
function draw() {
background(0);
fill (20);
// i'll put a rect that's the size of my capture here so that you can still understand the relationship between the capture image and the mouse
rect (0,0,capture.width,capture.height);
let pixelUnderMouse = capture.get(mouseX, mouseY);
processArray(pixelValues,pixelUnderMouse)
let averagePixelUnderMouse = transpose(pixelValues).map(e => mean(e))
fill(averagePixelUnderMouse);
rect(
300,
510,
300 * (averagePixelUnderMouse[0] / 255),
300 * (averagePixelUnderMouse[0] / 255)
);
fill(averagePixelUnderMouse[0], 0, 0);
rect(width * (averagePixelUnderMouse[0] / 255), 100, 100, 100);
fill(0, averagePixelUnderMouse[1], 0);
rect(width * (averagePixelUnderMouse[1] / 255), 210, 100, 100);
fill(0, 0, averagePixelUnderMouse[2]);
rect(width * (averagePixelUnderMouse[2] / 255), 320, 100, 100);
image(capture, 500, 510, 200, (200 * capture.height) / capture.width);
fill("white");
textSize(20);
text("xPosition: " + mouseX, 30, 480 + 50);
text("yPosition: " + mouseY, 30, 480 + 80);
text("capture: " + pixelUnderMouse, 30, 480 + 120);
}