This example shows how to wait for partyConnect()
and partyLoadShared()
using a callback instead of calling them in preload()
. This allows you to connect at sometime after your sketch starts.
Try this example in two browser windows at once!
let shared = false;
function preload() {
// nothing in preload, this example connects later and uses callbacks
// to know when the connection is ready
}
function setup() {
console.log("setup");
createCanvas(400, 400);
const button = createButton("connect").mousePressed(connectToParty);
button.parent(document.querySelector("main"));
}
function connectToParty() {
partyConnect("wss://demoserver.p5party.org", "callbacks", "main", () => {
console.log("connected!");
});
partyLoadShared("shared", { x: 0, y: 0 }, (s) => {
console.log("shared object loaded!");
shared = s;
});
}
function mousePressed() {
if (shared) {
shared.x = mouseX;
shared.y = mouseY;
}
}
function draw() {
if (!shared) {
background("#ffcccc");
fill("black");
text("click 'connect' button", 10, 20);
return;
}
background("#ccffcc");
noStroke();
fill("black");
text("shared loaded", 10, 20);
fill("#3333cc");
ellipse(shared.x, shared.y, 100, 100);
}
<!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>