Jump to content
Search Community

Davedave

Members
  • Posts

    1
  • Joined

  • Last visited

Davedave's Achievements

0

Reputation

  1. I'm trying to get a div to follow the mouse movement. I'm using mouse-position library to track movement, and gsap.ticker.add() to move the div. At the moment it works, but the div flickers back to its start position on each render because I'm not using state to manage the position. However if I use state, I can't update the state within the ticker.add() method – which I think I need to do? What's the best way to approach this? (I used codesandbox instead codepen because of react, hopefully thats ok!) link to codesandbox below: import React, { useEffect, useRef, forwardRef, useState } from 'react'; import { gsap } from 'gsap'; import useMouse from '@react-hook/mouse-position'; const styles = { circle: { width: 50, height: 50, borderRadius: '50%', background: 'black', }, wrapper: { width: '100vw', height: '100vh', position: 'relative', }, inner: { width: '100%', height: '100%', }, }; const Circle = forwardRef((props, ref) => { return <div style={styles.circle} ref={ref}></div>; }); export default function App() { let mouseTracker = useRef(null); let circleRef = null; let inner = null; const mouse = useMouse(mouseTracker, { enterDelay: 100, leaveDelay: 100, }); let pos = { x: inner ? inner.offsetWidth / 2 : 100, y: inner ? inner.offsetHeight / 2 : 100, }; useEffect(() => { gsap.ticker.add(() => { pos.x += (mouse.x - pos.x) * 0.1; pos.y += (mouse.y - pos.y) * 0.1; gsap.set(circleRef, { x: pos.x, y: pos.y }); }); }, [mouse]); return ( <div style={styles.wrapper} ref={mouseTracker}> <div style={styles.inner} ref={(el) => (inner = el)}> <Circle ref={(el) => (circleRef = el)} /> <p>mouse x: {mouse.x}</p> <p>mouse y: {mouse.y}</p> </div> </div> ); } https://codesandbox.io/s/mouse-follow-qr7pg?file=/src/App.js
×
×
  • Create New...