'Framer Motion - Making a div randomly move across the page

I am new to using Framer Motion but I do love the library a lot. Fantastic so far. However, I am stuck right now when trying to move a background div across the whole page.

https://codesandbox.io/s/svg-background-60ht8?file=/src/App.js

This is my codesandbox

I tried everything, read all the docs and I did get one tip to use Motionvalue and calculate the boundaries so the ball doesn't go off-screen. But I can't figure it out yet...

Does anyone know how to make the SVG/ball/div infinitely animate across the whole page? Thanks in advance!

EDIT:

It is moving randomly now, but on local machine the animation breaks and repeats when going outside the screen.



Solution 1:[1]

Not entirely sure if this kind of effect was what you were looking for, but I tried to add the random movement plus screen constraints in an example more akin to the DVD bouncing logo. However, I guess the motionValue should be used in all instances, since using state incurs rendering costs as well as a loss of precision.

I was not able to do the same demo using motion values, so that might be something worth exploring further.

Solution 2:[2]

I did something similar using MathRandom, with two state variables that represented both x and y positions on the screen, along with a setInterval() so it would change after a couple of seconds. Something like:

const Test = () => {

    const { height, width } = getDimensions();
    const [Position, setPosition] = useState({ x: 150, y: 150 })

    useEffect(() => {
            let timer = setInterval(() => {
                setPosition({
                    ...Position,
                    x: width * (1 - Math.random()) - 250,
                    y: height * (1 - Math.random()) - 250,
                }, 1500)
                
            return () => {
                clearInterval(timer)
            }
        }, [Position])

    return (
            <div className="screen">
              <div className='Animate' style={{
                    top: Position.y,
                    left: Position.x,
                    borderRadius: 100,
                    height: 100,
                    width: 100,
                    ...
                }} 
              />
         </div>
    )
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ferran Buireu
Solution 2 Cody Gray