This example builds on the hello_party
example, adding a history of user clicks using a shared array.
It also demonstrates a common pattern of initializing the shared object in setup using partyIsHost()
and partySetShrared()
together.
By using partyIsHost()
in setup we can determine if this client is the only/first client in the room, and if so, initialize the shared object. Using partySetShared()
sets all the values at once and removes any properties that might be left over from earlier development.
Try this example in two browser windows at once!
let shared;
function preload() {
partyConnect("wss://demoserver.p5party.org", "click_history");
shared = partyLoadShared("globals", {
x: 0,
y: 0,
color: "white",
clickHistory: [],
});
}
function setup() {
createCanvas(400, 400);
noStroke();
}
function draw() {
background("#ffcccc");
// read shared data
fill(shared.color);
ellipse(shared.x, shared.y, 100, 100);
fill("#000066");
for (const p of shared.clickHistory) {
ellipse(p.x, p.y, 20, 20);
}
}
function keyPressed() {
// write shared data
if (key === " ") {
shared.clickHistory = [];
return false;
}
}
function mousePressed(e) {
// write shared data
shared.x = mouseX;
shared.y = mouseY;
shared.color = color(random(255), random(255), random(255)).toString();
shared.clickHistory.push({ x: mouseX, y: mouseY });
}
<!DOCTYPE html>
<html>
<head> </head>
<body>
<main></main>
<div id="readme"></div>
<h2>index.js</h2>
<div id="source-javascript"></div>
<h2>index.html</h2>
<div id="source-html"></div>
<script src="https://cdn.jsdelivr.net/npm/p5@1.4.1/lib/p5.js"></script>
<script src="/dist/p5.party.js"></script>
<script src="index.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.0.3/highlight.min.js"></script>
<link rel="stylesheet" href="/examples.css" />
<script src="/examples.js" type="module"></script>
</body>
</html>