Public
Edited
Aug 27, 2024
2 forks
Importers
1 star
Insert cell
Insert cell
Insert cell
Insert cell
function viewHandler(canvas, callback) {
let theta = 0.6;
let phi = Math.PI/2;
let radius = 8;
let angleIncrement = 0.1;
let radiusIncrement = 0.2;
let minRadius = 0.2;
let maxRadius = 20;
let isDragging = false;
let previousMousePosition = { x: 0, y: 0 };
function updateMatrix() {
if(theta < -Math.PI/2) {
theta = -Math.PI/2;
}
if(theta > Math.PI/2) {
theta = Math.PI/2;
}
if(radius < minRadius) {
radius = minRadius;
}
if(radius > maxRadius) {
radius = maxRadius;
}
let x = radius * Math.cos(theta) * Math.cos(phi);
let y = radius * Math.sin(theta);
let z = radius * Math.cos(theta) * Math.sin(phi);
callback(x,y,z);
}
canvas.setAttribute("tabindex","0");
canvas.addEventListener('keydown', function(event) {
event.preventDefault();
switch (event.key) {
case 'ArrowUp':
theta += angleIncrement;
break;
case '0':
radius = 8;
theta = 0.6;
phi = Math.PI/2;
break;
case 'ArrowDown':
theta -= angleIncrement;
break;
case 'ArrowLeft':
phi += angleIncrement;
break;
case 'ArrowRight':
phi -= angleIncrement;
break;
case '+':
radius -= radiusIncrement;
break;
case '-':
radius += radiusIncrement;
break;
default:
return;
}
updateMatrix();
});

canvas.addEventListener('mousedown', ev => {
isDragging = true;
previousMousePosition.x = ev.offsetX;
previousMousePosition.y = ev.offsetY;
});
canvas.addEventListener('touchstart', ev => {
ev.preventDefault();
isDragging = true;
previousMousePosition.x = ev.targetTouches[0].clientX;
previousMousePosition.y = ev.targetTouches[0].clientY;
});
canvas.addEventListener('mouseup', () => { isDragging = false });
canvas.addEventListener('touchend', () => { isDragging = false });
canvas.addEventListener('mousemove', ev => {
if(isDragging) {
let dmx = ev.offsetX - previousMousePosition.x;
let dmy = ev.offsetY - previousMousePosition.y;
phi += dmx * angleIncrement * 0.1;
theta += dmy * angleIncrement * 0.1;
previousMousePosition.x = ev.offsetX;
previousMousePosition.y = ev.offsetY;
updateMatrix();
}
});
canvas.addEventListener('touchmove', ev => {
ev.preventDefault();
if(isDragging) {
let dmx = ev.targetTouches[0].clientX - previousMousePosition.x;
let dmy = ev.targetTouches[0].clientY - previousMousePosition.y;
phi += dmx * angleIncrement * 0.1;
theta += dmy * angleIncrement * 0.1;
previousMousePosition.x = ev.targetTouches[0].clientX;
previousMousePosition.y = ev.targetTouches[0].clientY;
updateMatrix();
}
});
canvas.addEventListener('wheel', ev => {
ev.preventDefault();
radius -= ev.deltaY * 0.01;
updateMatrix();
});

updateMatrix();
}
Insert cell
Insert cell
import {simpleCubeCanvas as cube} from "@rmauro/simple-webgl-cube"
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