From b95a2af981c903489631d7a9a3aa04cab8b18c5a Mon Sep 17 00:00:00 2001 From: Sam Nystrom Date: Sun, 10 Mar 2024 16:22:17 -0400 Subject: Add grid lines and ticks to Plot node --- src/nodes/Plot.tsx | 73 +++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 61 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/src/nodes/Plot.tsx b/src/nodes/Plot.tsx index fbec1f4..649246a 100644 --- a/src/nodes/Plot.tsx +++ b/src/nodes/Plot.tsx @@ -1,4 +1,5 @@ import { NodeShell, InputAny, InputNumber, NodeComponentProps, NodeInfo } from '../node.tsx'; +import { useComputed } from '@preact/signals'; export interface PlotInputs { data: any; @@ -11,32 +12,80 @@ export interface PlotInputs { export interface PlotOutputs {} export const Plot = ({ id, x, y, inputs }: NodeComponentProps) => { + const { minX, maxX, minY, maxY } = inputs; const data = inputs.data.value; const width = 400; const height = 400; - const dx = inputs.maxX.value - inputs.minX.value; - const dy = inputs.maxY.value - inputs.minY.value; + const xtickCount = 5; + const ytickCount = 5; + const dx = useComputed(() => maxX.value - minX.value); + const dy = useComputed(() => maxY.value - minY.value); let path = ''; if (data !== null && data.length > 3) { for (let i = 0; i < data.length; i += Math.max(2, Math.floor(data.length / 1000))) { if (i >= data.length) break; - const X = (data[i] - inputs.minX.value) / dx * width; - const Y = height - (data[i+1] - inputs.minY.value) / dy * height; + const X = (data[i] - minX.value) / dx.value * width; + const Y = height - (data[i+1] - minY.value) / dy.value * height; path += (i ? 'L' : 'M') + X + ' ' + Y; } } - //alert(dx); + + let xticks = []; + for (let x = minX.value; x <= maxX.value; x += dx.value / xtickCount) { + xticks.push([x.toFixed(1), (x - minX.value) / dx.value * width]); + } + let yticks = []; + for (let y = minY.value; y <= maxY.value; y += dy.value / ytickCount) { + yticks.push([y.toFixed(1), height - (y - minY.value) / dy.value * height]); + } + + const onMouseDown = (event: MouseEvent) => { + event.stopPropagation(); + const onMouseMove = (event: MouseEvent) => { + minX.value -= event.movementX / width * dx.value; + minY.value += event.movementY / height * dy.value; + }; + const onMouseUp = () => { + document.removeEventListener('mousemove', onMouseMove); + document.removeEventListener('mouseup', onMouseUp); + }; + document.addEventListener('mousemove', onMouseMove); + document.addEventListener('mouseup', onMouseUp); + }; + return ( - - - - + + + +
  • - - + + {xticks.map(([lbl, x]) => ( + <> + + + {lbl} + + ))} + {yticks.map(([lbl, y]) => ( + <> + + + {lbl} + + ))} + + + +
  • @@ -47,4 +96,4 @@ export const PlotNode: NodeInfo = { component: Plot, func: () => ({}), inputs: { data: null, minX: -10, minY: -10, maxX: 10, maxY: 10 }, -}; \ No newline at end of file +}; -- cgit v1.2.3