hell yeah i love canvas rendering

This commit is contained in:
ari melody 2025-03-15 17:54:58 +00:00
parent 3f3164bc15
commit ecda8dde24
Signed by: ari
GPG key ID: 60B5F0386E3DDB7E
3 changed files with 188 additions and 200 deletions

View file

@ -17,8 +17,9 @@ type CursorClient struct {
ID int32 ID int32
Conn *websocket.Conn Conn *websocket.Conn
Route string Route string
X int16 X float32
Y int16 Y float32
Click bool
Disconnected bool Disconnected bool
} }
@ -91,7 +92,7 @@ func handleClient(client *CursorClient) {
if otherClient.ID == client.ID { continue } if otherClient.ID == client.ID { continue }
if otherClient.Route != client.Route { continue } if otherClient.Route != client.Route { continue }
client.Send([]byte(fmt.Sprintf("join:%d", otherClient.ID))) client.Send([]byte(fmt.Sprintf("join:%d", otherClient.ID)))
client.Send([]byte(fmt.Sprintf("pos:%d:%d:%d", otherClient.ID, otherClient.X, otherClient.Y))) client.Send([]byte(fmt.Sprintf("pos:%d:%f:%f", otherClient.ID, otherClient.X, otherClient.Y)))
} }
mutex.Unlock() mutex.Unlock()
broadcast <- CursorMessage{ broadcast <- CursorMessage{
@ -118,15 +119,26 @@ func handleClient(client *CursorClient) {
client.Route, client.Route,
[]*CursorClient{ client }, []*CursorClient{ client },
} }
case "click":
if len(args) < 2 { return }
click := 0
if args[1][0] == '1' {
click = 1
}
broadcast <- CursorMessage{
[]byte(fmt.Sprintf("click:%d:%d", client.ID, click)),
client.Route,
[]*CursorClient{ client },
}
case "pos": case "pos":
if len(args) < 3 { return } if len(args) < 3 { return }
x, err := strconv.ParseInt(args[1], 10, 32) x, err := strconv.ParseFloat(args[1], 32)
y, err := strconv.ParseInt(args[2], 10, 32) y, err := strconv.ParseFloat(args[2], 32)
if err != nil { return } if err != nil { return }
client.X = int16(x) client.X = float32(x)
client.Y = int16(y) client.Y = float32(y)
broadcast <- CursorMessage{ broadcast <- CursorMessage{
[]byte(fmt.Sprintf("pos:%d:%d:%d", client.ID, client.X, client.Y)), []byte(fmt.Sprintf("pos:%d:%f:%f", client.ID, client.X, client.Y)),
client.Route, client.Route,
[]*CursorClient{ client }, []*CursorClient{ client },
} }

View file

@ -1,13 +1,14 @@
import config from './config.js'; import config from './config.js';
const CURSOR_TICK_RATE = 1000/30;
const CURSOR_LERP_RATE = 1/100; const CURSOR_LERP_RATE = 1/100;
const CURSOR_FUNCHAR_RATE = 20; const CURSOR_FUNCHAR_RATE = 20;
const CURSOR_CHAR_MAX_LIFE = 5000; const CURSOR_CHAR_MAX_LIFE = 5000;
const CURSOR_MAX_CHARS = 64; const CURSOR_MAX_CHARS = 64;
/** @type HTMLElement */ /** @type HTMLCanvasElement */
let cursorContainer; let canvas;
/** @type CanvasRenderingContext2D */
let ctx;
/** @type Cursor */ /** @type Cursor */
let myCursor; let myCursor;
/** @type Map<number, Cursor> */ /** @type Map<number, Cursor> */
@ -19,11 +20,12 @@ let ws;
let running = false; let running = false;
let lastUpdate = 0; let lastUpdate = 0;
let cursorBoxHeight = 0;
let cursorBoxRadius = 0;
let cursorIDFontSize = 0;
let cursorCharFontSize = 0;
class Cursor { class Cursor {
/** @type HTMLElement */
#element;
/** @type HTMLElement */
#charElement;
#funCharCooldown = CURSOR_FUNCHAR_RATE; #funCharCooldown = CURSOR_FUNCHAR_RATE;
/** /**
@ -32,46 +34,20 @@ class Cursor {
* @param {number} y * @param {number} y
*/ */
constructor(id, x, y) { constructor(id, x, y) {
this.id = id;
// real coordinates (canonical) // real coordinates (canonical)
this.x = x; this.x = x;
this.y = y; this.y = y;
// render coordinates (interpolated) // render coordinates (interpolated)
this.rx = x; this.rx = x;
this.ry = y; this.ry = y;
this.msg = ''; this.msg = '';
/** @type Array<FunChar> */
this.funChars = new Array(); this.funChars = new Array();
this.colour = randomColour();
const element = document.createElement('i'); this.click = false;
element.classList.add('cursor');
const colour = randomColour();
element.style.borderColor = colour;
element.style.color = colour;
cursorContainer.appendChild(element);
this.#element = element;
const char = document.createElement('i');
char.className = 'char';
cursorContainer.appendChild(char);
this.#charElement = char;
this.setID(id);
}
destroy() {
this.#element.remove();
this.#charElement.remove();
this.funChars.forEach(char => {
char.destroy();
});
}
/**
* @param {number} x
* @param {number} y
*/
move(x, y) {
this.x = x;
this.y = y;
} }
/** /**
@ -80,64 +56,80 @@ class Cursor {
update(deltaTime) { update(deltaTime) {
this.rx += (this.x - this.rx) * CURSOR_LERP_RATE * deltaTime; this.rx += (this.x - this.rx) * CURSOR_LERP_RATE * deltaTime;
this.ry += (this.y - this.ry) * CURSOR_LERP_RATE * deltaTime; this.ry += (this.y - this.ry) * CURSOR_LERP_RATE * deltaTime;
this.#element.style.left = this.rx + 'px';
this.#element.style.top = this.ry + 'px';
this.#charElement.style.left = this.rx + 'px';
this.#charElement.style.top = (this.ry - 24) + 'px';
if (this.#funCharCooldown > 0) if (this.#funCharCooldown > 0)
this.#funCharCooldown -= deltaTime; this.#funCharCooldown -= deltaTime;
if (this.msg.length > 0) { const x = this.rx * innerWidth - scrollX;
if (config.cursorFunMode === true) { const y = this.ry * innerHeight - scrollY;
const onBackground = ctx.fillStyle = getComputedStyle(document.body).getPropertyValue('--on-background');
if (config.cursorFunMode === true) {
if (this.msg.length > 0) {
if (this.#funCharCooldown <= 0) { if (this.#funCharCooldown <= 0) {
this.#funCharCooldown = CURSOR_FUNCHAR_RATE; this.#funCharCooldown = CURSOR_FUNCHAR_RATE;
if (this.funChars.length >= CURSOR_MAX_CHARS) { if (this.funChars.length >= CURSOR_MAX_CHARS) {
const char = this.funChars.shift(); this.funChars.shift();
char.destroy();
} }
const yOffset = -20; const yOffset = -10 / innerHeight;
const accelMultiplier = 0.002; const accelMultiplier = 0.002;
this.funChars.push(new FunChar( this.funChars.push(new FunChar(
this.x + window.scrollX, this.y + window.scrollY + yOffset, this.x, this.y + yOffset,
(this.x - this.rx) * accelMultiplier, (this.y - this.ry) * accelMultiplier, (this.x - this.rx) * accelMultiplier, (this.y - this.ry) * accelMultiplier,
this.msg)); this.msg));
} }
} else {
this.#charElement.innerText = this.msg;
} }
} else {
this.#charElement.innerText = ''; this.funChars.forEach(char => {
if (char.life > CURSOR_CHAR_MAX_LIFE ||
char.y - scrollY > innerHeight ||
char.x < 0 ||
char.x * innerWidth - scrollX > innerWidth
) {
this.funChars = this.funChars.filter(c => c !== this);
return;
}
char.update(deltaTime);
});
} else if (this.msg.length > 0) {
ctx.font = 'normal bold ' + cursorCharFontSize + 'px monospace';
ctx.fillStyle = onBackground;
ctx.fillText(
this.msg,
(x + 6) * devicePixelRatio,
(y + -8) * devicePixelRatio);
} }
this.funChars.forEach(char => { const lightTheme = matchMedia && matchMedia('(prefers-color-scheme: light)').matches;
if (char.life > CURSOR_CHAR_MAX_LIFE ||
char.y > document.body.clientHeight ||
char.x < 0 ||
char.x > document.body.clientWidth
) {
this.funChars = this.funChars.filter(c => c !== this);
char.destroy();
return;
}
char.update(deltaTime);
});
}
setID(id) { if (lightTheme)
this.id = id; ctx.filter = 'saturate(5) brightness(0.8)';
this.#element.id = 'cursor' + id;
this.#element.innerText = '0x' + id.toString(16).slice(0, 8).padStart(8, '0');
}
/** const idText = '0x' + this.id.toString(16).padStart(8, '0');
* @param {boolean} active const colour = this.click ? onBackground : this.colour;
*/
click(active) { ctx.beginPath();
if (active) ctx.roundRect(
this.#element.classList.add('click'); (x) * devicePixelRatio,
else (y) * devicePixelRatio,
this.#element.classList.remove('click'); (12 + 7.2 * idText.length) * devicePixelRatio,
cursorBoxHeight,
cursorBoxRadius);
ctx.closePath();
ctx.fillStyle = lightTheme ? '#fff8' : '#0008';
ctx.fill();
ctx.strokeStyle = colour;
ctx.lineWidth = devicePixelRatio;
ctx.stroke();
ctx.font = cursorIDFontSize + 'px monospace';
ctx.fillStyle = colour;
ctx.fillText(
idText,
(x + 6) * devicePixelRatio,
(y + 14) * devicePixelRatio);
ctx.filter = '';
} }
} }
@ -152,20 +144,12 @@ class FunChar {
constructor(x, y, xa, ya, text) { constructor(x, y, xa, ya, text) {
this.x = x; this.x = x;
this.y = y; this.y = y;
this.xa = xa + Math.random() * .2 - .1; this.xa = xa + Math.random() * .0005 - .00025;
this.ya = ya + Math.random() * -.25; this.ya = ya + Math.random() * -.00025;
this.r = this.xa * 100; this.r = this.xa * 1000;
this.ra = this.r * 0.01; this.ra = this.r * 0.01;
this.text = text;
this.life = 0; this.life = 0;
const char = document.createElement('i');
char.className = 'funchar';
char.innerText = text;
char.style.left = x + 'px';
char.style.top = y + 'px';
char.style.transform = `rotate(${this.r}deg)`;
this.element = char;
cursorContainer.appendChild(this.element);
} }
/** /**
@ -177,15 +161,27 @@ class FunChar {
this.x += this.xa * deltaTime; this.x += this.xa * deltaTime;
this.y += this.ya * deltaTime; this.y += this.ya * deltaTime;
this.r += this.ra * deltaTime; this.r += this.ra * deltaTime;
this.ya = Math.min(this.ya + 0.0005 * deltaTime, 10); this.ya = Math.min(this.ya + 0.000001 * deltaTime, 10);
this.element.style.left = (this.x - window.scrollX) + 'px'; const x = this.x * innerWidth - scrollX;
this.element.style.top = (this.y - window.scrollY) + 'px'; const y = this.y * innerHeight - scrollY;
this.element.style.transform = `rotate(${this.r}deg)`;
}
destroy() { const translateOffset = {
this.element.remove(); x: (x + 7.2) * devicePixelRatio,
y: (y - 7.2) * devicePixelRatio,
};
ctx.translate(translateOffset.x, translateOffset.y);
ctx.rotate(this.r);
ctx.translate(-translateOffset.x, -translateOffset.y);
ctx.font = 'normal bold ' + cursorCharFontSize + 'px monospace';
ctx.fillStyle = getComputedStyle(document.body).getPropertyValue('--on-background');
ctx.fillText(
this.text,
x * devicePixelRatio,
y * devicePixelRatio);
ctx.resetTransform();
} }
} }
@ -205,18 +201,37 @@ function randomColour() {
/** /**
* @param {MouseEvent} event * @param {MouseEvent} event
*/ */
let mouseMoveLock = false;
const mouseMoveCooldown = 1000/30;
function handleMouseMove(event) { function handleMouseMove(event) {
if (!myCursor) return; if (!myCursor) return;
if (ws && ws.readyState == WebSocket.OPEN)
ws.send(`pos:${event.x}:${event.y}`); const x = event.pageX / innerWidth;
myCursor.move(event.x, event.y); const y = event.pageY / innerHeight;
const f = 10000; // four digit floating-point precision
if (!mouseMoveLock) {
mouseMoveLock = true;
if (ws && ws.readyState == WebSocket.OPEN)
ws.send(`pos:${Math.round(x * f) / f}:${Math.round(y * f) / f}`);
setTimeout(() => {
mouseMoveLock = false;
}, mouseMoveCooldown);
}
myCursor.x = x;
myCursor.y = y;
} }
function handleMouseDown() { function handleMouseDown() {
myCursor.click(true); myCursor.click = true;
if (ws && ws.readyState == WebSocket.OPEN)
ws.send('click:1');
} }
function handleMouseUp() { function handleMouseUp() {
myCursor.click(false); myCursor.click = false;
if (ws && ws.readyState == WebSocket.OPEN)
ws.send('click:0');
} }
/** /**
@ -238,56 +253,69 @@ function handleKeyUp() {
} }
/** /**
* @param {number} time * @param {number} timestamp
*/ */
function updateCursors(time) { function update(timestamp) {
if (!running) return; if (!running) return;
const deltaTime = time - lastUpdate; const deltaTime = timestamp - lastUpdate;
lastUpdate = timestamp;
ctx.clearRect(0, 0, canvas.width, canvas.height);
cursors.forEach(cursor => { cursors.forEach(cursor => {
cursor.update(deltaTime); cursor.update(deltaTime);
}); });
lastUpdate = time; requestAnimationFrame(update);
requestAnimationFrame(updateCursors); }
function handleWindowResize() {
canvas.width = innerWidth * devicePixelRatio;
canvas.height = innerHeight * devicePixelRatio;
cursorBoxHeight = 20 * devicePixelRatio;
cursorBoxRadius = 4 * devicePixelRatio;
cursorIDFontSize = 12 * devicePixelRatio;
cursorCharFontSize = 20 * devicePixelRatio;
} }
function cursorSetup() { function cursorSetup() {
if (running) throw new Error('Only one instance of Cursor can run at a time.'); if (running) throw new Error('Only one instance of Cursor can run at a time.');
running = true; running = true;
cursorContainer = document.createElement('div'); canvas = document.createElement('canvas');
cursorContainer.id = 'cursors'; canvas.id = 'cursors';
document.body.appendChild(cursorContainer); handleWindowResize();
document.body.appendChild(canvas);
myCursor = new Cursor("You!", window.innerWidth / 2, window.innerHeight / 2); ctx = canvas.getContext('2d');
myCursor = new Cursor('You!', innerWidth / 2, innerHeight / 2);
cursors.set(0, myCursor); cursors.set(0, myCursor);
addEventListener('resize', handleWindowResize);
document.addEventListener('mousemove', handleMouseMove); document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mousedown', handleMouseDown); document.addEventListener('mousedown', handleMouseDown);
document.addEventListener('mouseup', handleMouseUp); document.addEventListener('mouseup', handleMouseUp);
document.addEventListener('keypress', handleKeyPress); document.addEventListener('keypress', handleKeyPress);
document.addEventListener('keyup', handleKeyUp); document.addEventListener('keyup', handleKeyUp);
requestAnimationFrame(updateCursors); requestAnimationFrame(update);
ws = new WebSocket("/cursor-ws"); ws = new WebSocket('/cursor-ws');
ws.addEventListener('open', () => {
console.log('Cursor connected to server successfully.');
ws.addEventListener("open", () => { ws.send(`loc:${location.pathname}`);
console.log("Cursor connected to server successfully.");
ws.send(`loc:${window.location.pathname}`);
}); });
ws.addEventListener("error", error => { ws.addEventListener('error', error => {
console.error("Cursor WebSocket error:", error); console.error('Cursor WebSocket error:', error);
}); });
ws.addEventListener("close", () => { ws.addEventListener('close', () => {
console.log("Cursor connection closed."); console.log('Cursor connection closed.');
}); });
ws.addEventListener('message', event => {
ws.addEventListener("message", event => { const args = String(event.data).split(':');
const args = String(event.data).split(":");
if (args.length == 0) return; if (args.length == 0) return;
let id = 0; let id = 0;
@ -300,7 +328,7 @@ function cursorSetup() {
switch (args[0]) { switch (args[0]) {
case 'id': { case 'id': {
myCursor.setID(Number(args[1])); myCursor.id = Number(args[1]);
break; break;
} }
case 'join': { case 'join': {
@ -310,7 +338,6 @@ function cursorSetup() {
} }
case 'leave': { case 'leave': {
if (!cursor || cursor === myCursor) break; if (!cursor || cursor === myCursor) break;
cursors.get(id).destroy();
cursors.delete(id); cursors.delete(id);
break; break;
} }
@ -324,33 +351,37 @@ function cursorSetup() {
cursor.msg = ''; cursor.msg = '';
break; break;
} }
case 'click': {
if (!cursor || cursor === myCursor) break;
cursor.click = args[2] == '1';
break;
}
case 'pos': { case 'pos': {
if (!cursor || cursor === myCursor) break; if (!cursor || cursor === myCursor) break;
cursor.move(Number(args[2]), Number(args[3])); cursor.x = Number(args[2]);
cursor.y = Number(args[3]);
break; break;
} }
default: { default: {
console.warn("Cursor: Unknown command received from server:", args[0]); console.warn('Cursor: Unknown command received from server:', args[0]);
break; break;
} }
} }
}); });
console.log(`Cursor tracking @ ${window.location.pathname}`); console.log(`Cursor tracking @ ${location.pathname}`);
} }
function cursorDestroy() { function cursorDestroy() {
if (!running) return; if (!running) return;
removeEventListener('resize', handleWindowResize);
document.removeEventListener('mousemove', handleMouseMove); document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mousedown', handleMouseDown); document.removeEventListener('mousedown', handleMouseDown);
document.removeEventListener('mouseup', handleMouseUp); document.removeEventListener('mouseup', handleMouseUp);
document.removeEventListener('keypress', handleKeyPress); document.removeEventListener('keypress', handleKeyPress);
document.removeEventListener('keyup', handleKeyUp); document.removeEventListener('keyup', handleKeyUp);
cursors.forEach(cursor => {
cursor.destroy();
});
cursors.clear(); cursors.clear();
myCursor = null; myCursor = null;

View file

@ -1,64 +1,9 @@
#cursors i.cursor { canvas#cursors {
position: fixed;
padding: 4px;
display: block;
z-index: 1000;
background: #0008;
border: 2px solid #808080;
border-radius: 2px;
font-style: normal;
font-size: 10px;
font-weight: bold;
white-space: nowrap;
}
#cursors i.cursor.click {
color: var(--on-background) !important;
border-color: var(--on-background) !important;
}
#cursors i.char {
position: absolute;
margin: 0;
font-style: normal;
font-size: 20px;
font-weight: bold;
color: var(--on-background);
}
#cursors i.funchar {
position: absolute;
margin: 0;
display: block;
z-index: 1000;
font-style: normal;
font-size: 20px;
font-weight: bold;
color: var(--on-background);
}
#cursors {
width: 100vw;
height: 100vh;
position: fixed; position: fixed;
top: 0; top: 0;
left: 0; left: 0;
width: 100vw;
z-index: 1000; height: 100vh;
overflow: clip;
user-select: none;
pointer-events: none; pointer-events: none;
} z-index: 100;
@media (prefers-color-scheme: light) {
#cursors i.cursor {
filter: saturate(5) brightness(0.8);
background: #fff8;
}
} }