Newer
Older
import { line, curveBasis } from "d3-shape"
import {
canvas,
connectedPeers,
peerButton,
peerIDElem,
userIDElem,
} from "./elements.js"
import { connect } from "./room.js"
const pathElems = new Map()
const addOrUpdatePathElem = (id, points) => {
const lineFn = line()
.x((d) => d[0])
.y((d) => d[1])
.curve(curveBasis)
let pathElem = pathElems.get(id)
if (pathElem == null) {
pathElem = document.createElementNS("http://www.w3.org/2000/svg", "path")
pathElem.setAttribute("stroke", "blue")
pathElem.setAttribute("stroke-width", 3)
pathElem.setAttribute("fill", "none")
pathElem.setAttribute("pointer-events", "none")
canvas.appendChild(pathElem)
pathElems.set(id, pathElem)
Moritz Langenstein
committed
if (points.length == 0) {
pathElem.removeAttribute("d")
return pathElem
}
Moritz Langenstein
committed
pathElem.setAttribute("d", lineFn(points))
return pathElem
}
Moritz Langenstein
committed
connect("imperial").then((room) => {
let painting = false
let currentPathID = null
Moritz Langenstein
committed
userIDElem.value = room.ownID || ""
room.addEventListener("allocateOwnID", ({ detail: id }) => {
userIDElem.value = id
})
Moritz Langenstein
committed
room.addEventListener("userJoin", ({ detail: id }) => {
const peerElem = document.createElement("li")
peerElem.innerHTML = id
connectedPeers.appendChild(peerElem)
})
Moritz Langenstein
committed
room.addEventListener("userLeave", ({ detail: id }) => {
for (const peerElem of connectedPeers.children) {
if (peerElem.innerHTML == id) {
connectedPeers.removeChild(peerElem)
}
Moritz Langenstein
committed
}
Moritz Langenstein
committed
room.addEventListener("addOrUpdatePath", ({ detail: { id, points } }) => {
addOrUpdatePathElem(id, points)
})
Moritz Langenstein
committed
canvas.addEventListener("mousedown", (e) => {
currentPathID = room.addPath([e.offsetX, e.offsetY])
Moritz Langenstein
committed
painting = true
Moritz Langenstein
committed
Moritz Langenstein
committed
painting = false
Moritz Langenstein
committed
Moritz Langenstein
committed
if (painting) {
room.extendPath(currentPathID, [e.offsetX, e.offsetY])
Moritz Langenstein
committed
}
Moritz Langenstein
committed
peerButton.addEventListener("click", () => {
const peerID = peerIDElem.value
if (peerID == "") {
return
Moritz Langenstein
committed
}
room.inviteUser(peerID)
peerIDElem.value = ""
Moritz Langenstein
committed
})