Cake exmaple
The snippet can be accessed without any authentication.
Authored by
Peter Sutton
example.js 1.93 KiB
import p5 from 'p5';
import 'p5/lib/addons/p5.sound';
import { P5VideoRoom } from './lib/p5videoroom/P5VideoRoom';
import { roomId } from './roomId';
import './style.scss';
/**
* Define our sketch.
*
* @param {p5} sketch An instance of p5, where you would normally call a p5
* function, e.g., fill(0), you now call sketch.fill(0).
*/
const videoRoomSketch = (sketch) => {
// Create the video room. This sets up a video call and asks the user for
// permission to use their webcam/microphone
const videoRoom = new P5VideoRoom(sketch, roomId);
const width = 400;
const height = 400;
sketch.setup = () => {
sketch.createCanvas(width, height);
};
// Browsers won't let us play sound until there is a user interaction. So we
// track whether one has occured here. We will use this to decide whether to
// unmute the videos.
let hasInteracted = false;
sketch.mousePressed = () => {
hasInteracted = true;
};
const cakes = []; // 1. Place to store events;
sketch.draw = () => {
sketch.background(0);
videoRoom.forEachRemoteVideo((rV) => {
const { data } = rV;
if (data === null) { return; }
// 3. Store incoming events.
if (data.giveCake) {
cakes.push({ x: data.x, y: data.y });
}
const element = rV.video.elt;
element.muted = !hasInteracted;
sketch.image(rV.video, data.x, data.y, 100, 100);
});
// 4. Display recieved events
cakes.forEach(({ x, y }) => {
sketch.fill(255, 0, 0);
sketch.circle(x, y, 34);
});
const x = sketch.mouseX;
const y = sketch.mouseY;
if (videoRoom.localVideo !== null) {
sketch.image(videoRoom.localVideo, x, y, 100, 100);
}
// 2. Send event to people in room
videoRoom.sendData({ x, y, giveCake: sketch.mouseIsPressed });
if (sketch.mouseIsPressed) { // 5. Also give yourself a cake
cakes.push({ x, y });
}
};
};
// Create and run the sketch.
new p5(videoRoomSketch);
Please register or sign in to comment