glslCanvas icon indicating copy to clipboard operation
glslCanvas copied to clipboard

setMouse / Faulty mouse coordinates

Open moritzsalla opened this issue 3 years ago • 2 comments

The .setMouse() function returns faulty values. Please excuse if I am using the function incorrectly.

For example, when passing sandbox.useMouse({ x: 0, y: 0 }) and logging sandbox.uniforms, u_mouse returns as follows:

{
    "name": "u_mouse",
    "type": "vec2",
    "value": [
        1.785604900459418,
        149.35220838052095
    ],
    "method": "uniform2f",
    "location": {}
}

In case the function maps the coordinates to the canvas element, here is my react implementation:

const Canvas = () => {
  const canvasRef = useRef();

  const { current } = canvasRef;

  useEffect(() => {
    if (current) {
      const sandbox = new GlslCanvas(current);
      sandbox.load(program.frag);

      sandbox.setUniform('u_texture', testImg);
      console.log(sandbox);
      sandbox.setMouse({ x: 0, y: 0 });
    }
  }, [current, mouse]);

  return <canvas ref={canvasRef} />;
};

moritzsalla avatar Nov 03 '21 08:11 moritzsalla

Same issue. Any good workaround?

eriksachse avatar Jan 16 '23 15:01 eriksachse

Same issue. Any good workaround?

Couldn't make it happen with glsl-canvas but made a custom implementation by passing a u_pointer uniform.

import Canvas from 'glsl-canvas-js/dist/cjs/canvas/canvas'
import { useMove } from '@use-gesture/react'

const canvasElemRef = useRef()
const shaderProgramRef = useRef()
const matchesFine = useMatchMedia(MEDIA_QUERIES.fine)

useEffect(() => {
  const canvasElem = canvasElemRef.current

  // Check if a canvas element exists...
  if (!canvasElem) return

  // instantiate glsl-canvas
  shaderProgramRef.current = new Canvas(canvasElem, {})

  // cleanup glsl-canvas
  return () => {
    shaderProgramRef.current.pause()
    shaderProgramRef.current = null
  }
}, [canvasElemRef.current])

// https://use-gesture.netlify.app/docs/gestures/
useMove(
  ({ xy: [x, y] }) => {
    // If the program has not been initialised yet, return early.
    if (!canvasElemRef.current) return

    const normalisedCoords = [x, window.innerHeight - y * 0.5]

    canvasElemRef.current.setUniforms({ u_pointer: normalisedCoords })
  },
  {
    // ssr check - I'm using next.js
    target: typeof window === 'undefined' ? null : window,
    // ignore coarse pointers
    enabled: matchesFine,
  },
)

moritzsalla avatar Mar 27 '23 15:03 moritzsalla