Public
Edited
Nov 25, 2024
Insert cell
Insert cell
Insert cell
Insert cell
canvas = {
let canvas = html`
<canvas id='canvas'></canvas>
`;
let ctx = canvas.getContext("2d");
Object.assign(ctx.canvas, { width, height });

// Initialize the canvas
fillCanvas(ctx);

canvas.addEventListener("mousemove", (event) => {
let { layerX, layerY } = event;

Object.assign(mouseEvent, { x: layerX, y: layerY });
document.getElementById("powerbar").innerHTML = `
<p>X: ${mouseEvent.x} | Y: ${mouseEvent.y}</p>
`;
});

setInterval(onMouseMove, 20, ctx);

return canvas;
}
Insert cell
onMouseMove = (ctx) => {
let { x, y } = mouseEvent,
{ width, heigth } = ctx.canvas;

// Draw the background
fillCanvas(ctx);

// Draw the current mouse position
ctx.fillStyle = "white";
ctx.fillRect(x - 10, y - 10, 20, 20);

ctx.fillStyle = "red";

let n = dynamicData.mouseArray.length,
w = parseInt(width * boxWidth),
k = n > w ? 0 : w - n;

dynamicData.mouseArray.slice(Math.max(n - w, 0)).map((m, i) => {
let { x, y } = m;
ctx.fillRect(i - 1 + k, y - 1, 2, 2);
});
}
Insert cell
{
let n;
let foo = () => {
let { x, y } = mouseEvent;
dynamicData.mouseArray.push({ x, y });
n = dynamicData.mouseArray.length;
if (dynamicData.mouseArray.length > 10000) {
dynamicData.mouseArray = dynamicData.mouseArray.slice(n - 1000);
}
};

setInterval(foo, 20);
}
Insert cell
dynamicData = {
let mouseArray = [];
return Object.assign({}, { mouseArray });
}
Insert cell
mouseEvent = {
let x = 0,
y = 0;
return { x, y };
}
Insert cell
fillCanvas = (ctx) => {
// let ctx = canvas.getContext("2d");
let k = parseInt(boxWidth * 360),
{ width, height } = ctx.canvas;

ctx.fillStyle = "hsl(216deg 20% 90%)";
ctx.fillRect(0, 0, width, height);

ctx.fillStyle = "hsl(216deg 100% 13%)";
ctx.fillStyle = `hsl(${k}deg 100% 13%)`;
ctx.fillRect(0, 0, boxWidth * width, height);

// Draw the reference line
ctx.fillStyle = "#00ff00";
ctx.fillRect(0, height / 2 - 1, width, 2);

// ctx.canvas.style.background = "hsl(216deg 20% 90%)";
return ctx;
}
Insert cell
height = 200
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more