arimelody.me/public/script/cursor.js

404 lines
11 KiB
JavaScript
Raw Permalink Normal View History

import config from './config.js';
2025-03-14 00:33:59 +00:00
const CURSOR_LERP_RATE = 1/100;
2025-03-14 20:42:44 +00:00
const CURSOR_FUNCHAR_RATE = 20;
2025-03-14 00:33:59 +00:00
const CURSOR_CHAR_MAX_LIFE = 5000;
2025-03-14 20:42:44 +00:00
const CURSOR_MAX_CHARS = 64;
2025-03-15 17:54:58 +00:00
/** @type HTMLCanvasElement */
let canvas;
/** @type CanvasRenderingContext2D */
let ctx;
2025-03-14 00:33:59 +00:00
/** @type Cursor */
let myCursor;
/** @type Map<number, Cursor> */
let cursors = new Map();
2025-03-14 20:42:44 +00:00
/** @type WebSocket */
let ws;
2025-03-14 00:33:59 +00:00
let running = false;
2025-03-14 20:42:44 +00:00
let lastUpdate = 0;
2025-03-14 00:33:59 +00:00
2025-03-15 17:54:58 +00:00
let cursorBoxHeight = 0;
let cursorBoxRadius = 0;
let cursorIDFontSize = 0;
let cursorCharFontSize = 0;
2025-03-14 00:33:59 +00:00
class Cursor {
2025-03-14 20:42:44 +00:00
#funCharCooldown = CURSOR_FUNCHAR_RATE;
2025-03-14 00:33:59 +00:00
/**
2025-03-14 20:42:44 +00:00
* @param {string} id
2025-03-14 00:33:59 +00:00
* @param {number} x
* @param {number} y
*/
constructor(id, x, y) {
2025-03-15 17:54:58 +00:00
this.id = id;
2025-03-14 20:42:44 +00:00
// real coordinates (canonical)
2025-03-14 00:33:59 +00:00
this.x = x;
this.y = y;
2025-03-14 20:42:44 +00:00
// render coordinates (interpolated)
2025-03-14 00:33:59 +00:00
this.rx = x;
this.ry = y;
2025-03-15 17:54:58 +00:00
2025-03-14 20:42:44 +00:00
this.msg = '';
2025-03-15 17:54:58 +00:00
/** @type Array<FunChar> */
2025-03-14 20:42:44 +00:00
this.funChars = new Array();
2025-03-15 17:54:58 +00:00
this.colour = randomColour();
this.click = false;
2025-03-14 00:33:59 +00:00
}
/**
* @param {number} deltaTime
*/
update(deltaTime) {
this.rx += (this.x - this.rx) * CURSOR_LERP_RATE * deltaTime;
this.ry += (this.y - this.ry) * CURSOR_LERP_RATE * deltaTime;
2025-03-14 20:42:44 +00:00
if (this.#funCharCooldown > 0)
this.#funCharCooldown -= deltaTime;
2025-03-15 17:54:58 +00:00
const x = this.rx * innerWidth - scrollX;
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) {
2025-03-14 20:42:44 +00:00
if (this.#funCharCooldown <= 0) {
this.#funCharCooldown = CURSOR_FUNCHAR_RATE;
if (this.funChars.length >= CURSOR_MAX_CHARS) {
2025-03-15 17:54:58 +00:00
this.funChars.shift();
2025-03-14 20:42:44 +00:00
}
2025-03-15 17:54:58 +00:00
const yOffset = -10 / innerHeight;
2025-03-14 20:42:44 +00:00
const accelMultiplier = 0.002;
this.funChars.push(new FunChar(
2025-03-15 17:54:58 +00:00
this.x, this.y + yOffset,
2025-03-14 20:42:44 +00:00
(this.x - this.rx) * accelMultiplier, (this.y - this.ry) * accelMultiplier,
this.msg));
}
}
2025-03-14 00:33:59 +00:00
2025-03-15 17:54:58 +00:00
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);
}
2025-03-15 17:54:58 +00:00
const lightTheme = matchMedia && matchMedia('(prefers-color-scheme: light)').matches;
if (lightTheme)
ctx.filter = 'saturate(5) brightness(0.8)';
const idText = '0x' + this.id.toString(16).padStart(8, '0');
const colour = this.click ? onBackground : this.colour;
ctx.beginPath();
ctx.roundRect(
(x) * devicePixelRatio,
(y) * devicePixelRatio,
(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 = '';
}
2025-03-14 00:33:59 +00:00
}
class FunChar {
/**
* @param {number} x
* @param {number} y
* @param {number} xa
* @param {number} ya
* @param {string} text
*/
constructor(x, y, xa, ya, text) {
this.x = x;
this.y = y;
2025-03-15 17:54:58 +00:00
this.xa = xa + Math.random() * .0005 - .00025;
this.ya = ya + Math.random() * -.00025;
this.r = this.xa * 1000;
2025-03-14 00:33:59 +00:00
this.ra = this.r * 0.01;
2025-03-15 17:54:58 +00:00
this.text = text;
2025-03-14 00:33:59 +00:00
this.life = 0;
}
/**
* @param {number} deltaTime
*/
update(deltaTime) {
this.life += deltaTime;
this.x += this.xa * deltaTime;
this.y += this.ya * deltaTime;
this.r += this.ra * deltaTime;
2025-03-15 17:54:58 +00:00
this.ya = Math.min(this.ya + 0.000001 * deltaTime, 10);
const x = this.x * innerWidth - scrollX;
const y = this.y * innerHeight - scrollY;
const translateOffset = {
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();
2025-03-14 00:33:59 +00:00
}
}
/**
* @returns string
*/
function randomColour() {
const min = 128;
const range = 100;
const red = Math.round((min + Math.random() * range)).toString(16);
const green = Math.round((min + Math.random() * range)).toString(16);
const blue = Math.round((min + Math.random() * range)).toString(16);
return '#' + red + green + blue;
2025-03-14 00:33:59 +00:00
}
/**
* @param {MouseEvent} event
*/
2025-03-15 17:54:58 +00:00
let mouseMoveLock = false;
const mouseMoveCooldown = 1000/30;
2025-03-14 00:33:59 +00:00
function handleMouseMove(event) {
if (!myCursor) return;
2025-03-15 17:54:58 +00:00
const x = event.pageX / innerWidth;
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;
2025-03-14 00:33:59 +00:00
}
function handleMouseDown() {
2025-03-15 17:54:58 +00:00
myCursor.click = true;
if (ws && ws.readyState == WebSocket.OPEN)
ws.send('click:1');
}
function handleMouseUp() {
2025-03-15 17:54:58 +00:00
myCursor.click = false;
if (ws && ws.readyState == WebSocket.OPEN)
ws.send('click:0');
}
2025-03-14 00:33:59 +00:00
/**
* @param {KeyboardEvent} event
*/
2025-03-14 20:42:44 +00:00
function handleKeyPress(event) {
2025-03-14 00:33:59 +00:00
if (event.key.length > 1) return;
if (event.metaKey || event.ctrlKey) return;
2025-03-14 20:42:44 +00:00
if (myCursor.msg === event.key) return;
if (ws && ws.readyState == WebSocket.OPEN)
ws.send(`char:${event.key}`);
myCursor.msg = event.key;
2025-03-14 00:33:59 +00:00
}
function handleKeyUp() {
2025-03-14 20:42:44 +00:00
if (ws && ws.readyState == WebSocket.OPEN)
ws.send(`nochar`);
myCursor.msg = '';
2025-03-14 00:33:59 +00:00
}
/**
2025-03-15 17:54:58 +00:00
* @param {number} timestamp
2025-03-14 00:33:59 +00:00
*/
2025-03-15 17:54:58 +00:00
function update(timestamp) {
if (!running) return;
2025-03-15 17:54:58 +00:00
const deltaTime = timestamp - lastUpdate;
lastUpdate = timestamp;
ctx.clearRect(0, 0, canvas.width, canvas.height);
2025-03-14 00:33:59 +00:00
cursors.forEach(cursor => {
cursor.update(deltaTime);
});
2025-03-15 17:54:58 +00:00
requestAnimationFrame(update);
}
function handleWindowResize() {
canvas.width = innerWidth * devicePixelRatio;
canvas.height = innerHeight * devicePixelRatio;
cursorBoxHeight = 20 * devicePixelRatio;
cursorBoxRadius = 4 * devicePixelRatio;
cursorIDFontSize = 12 * devicePixelRatio;
cursorCharFontSize = 20 * devicePixelRatio;
2025-03-14 00:33:59 +00:00
}
function cursorSetup() {
if (running) throw new Error('Only one instance of Cursor can run at a time.');
running = true;
2025-03-15 17:54:58 +00:00
canvas = document.createElement('canvas');
canvas.id = 'cursors';
handleWindowResize();
document.body.appendChild(canvas);
ctx = canvas.getContext('2d');
2025-03-15 17:54:58 +00:00
myCursor = new Cursor('You!', innerWidth / 2, innerHeight / 2);
2025-03-14 00:33:59 +00:00
cursors.set(0, myCursor);
2025-03-15 17:54:58 +00:00
addEventListener('resize', handleWindowResize);
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mousedown', handleMouseDown);
document.addEventListener('mouseup', handleMouseUp);
2025-03-14 20:42:44 +00:00
document.addEventListener('keypress', handleKeyPress);
document.addEventListener('keyup', handleKeyUp);
2025-03-15 17:54:58 +00:00
requestAnimationFrame(update);
2025-03-14 20:42:44 +00:00
2025-03-15 17:54:58 +00:00
ws = new WebSocket('/cursor-ws');
ws.addEventListener('open', () => {
console.log('Cursor connected to server successfully.');
2025-03-14 20:42:44 +00:00
2025-03-15 17:54:58 +00:00
ws.send(`loc:${location.pathname}`);
2025-03-14 20:42:44 +00:00
});
2025-03-15 17:54:58 +00:00
ws.addEventListener('error', error => {
console.error('Cursor WebSocket error:', error);
2025-03-14 20:42:44 +00:00
});
2025-03-15 17:54:58 +00:00
ws.addEventListener('close', () => {
console.log('Cursor connection closed.');
2025-03-14 20:42:44 +00:00
});
2025-03-15 17:54:58 +00:00
ws.addEventListener('message', event => {
const args = String(event.data).split(':');
2025-03-14 20:42:44 +00:00
if (args.length == 0) return;
let id = 0;
/** @type Cursor */
let cursor;
if (args.length > 1) {
id = Number(args[1]);
cursor = cursors.get(id);
}
switch (args[0]) {
case 'id': {
myCursor.id = id;
2025-03-14 20:42:44 +00:00
break;
}
case 'join': {
if (id === myCursor.id) break;
cursors.set(id, new Cursor(id, 0, 0));
break;
}
case 'leave': {
if (!cursor || cursor === myCursor) break;
cursors.delete(id);
break;
}
case 'char': {
if (!cursor || cursor === myCursor) break;
cursor.msg = args[2];
break;
}
case 'nochar': {
if (!cursor || cursor === myCursor) break;
cursor.msg = '';
break;
}
2025-03-15 17:54:58 +00:00
case 'click': {
if (!cursor || cursor === myCursor) break;
cursor.click = args[2] == '1';
break;
}
2025-03-14 20:42:44 +00:00
case 'pos': {
if (!cursor || cursor === myCursor) break;
2025-03-15 17:54:58 +00:00
cursor.x = Number(args[2]);
cursor.y = Number(args[3]);
2025-03-14 20:42:44 +00:00
break;
}
default: {
2025-03-15 17:54:58 +00:00
console.warn('Cursor: Unknown command received from server:', args[0]);
2025-03-14 20:42:44 +00:00
break;
}
}
});
2025-03-15 17:54:58 +00:00
console.log(`Cursor tracking @ ${location.pathname}`);
2025-03-14 00:33:59 +00:00
}
function cursorDestroy() {
if (!running) return;
2025-03-15 17:54:58 +00:00
removeEventListener('resize', handleWindowResize);
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mousedown', handleMouseDown);
document.removeEventListener('mouseup', handleMouseUp);
2025-03-14 20:42:44 +00:00
document.removeEventListener('keypress', handleKeyPress);
document.removeEventListener('keyup', handleKeyUp);
ctx.clearRect(0, 0, canvas.width, canvas.height);
2025-03-14 00:33:59 +00:00
cursors.clear();
myCursor = null;
2025-03-14 20:42:44 +00:00
console.log(`Cursor no longer tracking.`);
running = false;
}
if (config.cursor === true) {
cursorSetup();
2025-03-14 00:33:59 +00:00
}
config.addListener('cursor', enabled => {
if (enabled === true)
cursorSetup();
else
cursorDestroy();
});