Advertisement
corp0

Untitled

Dec 12th, 2022
992
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, { useState, useEffect } from 'react';
  2.  
  3. function FloatingImage() {
  4.   const [x, setX] = useState(0);
  5.   const [y, setY] = useState(0);
  6.   const [dx, setDx] = useState(1);
  7.   const [dy, setDy] = useState(1);
  8.  
  9.   useEffect(() => {
  10.     const interval = setInterval(() => {
  11.       // Check if the image has reached the edge of the screen
  12.       if (x + dx > 100 || x + dx < 0) {
  13.         // Change the direction of the image
  14.         setDx(prevDx => -prevDx);
  15.       }
  16.  
  17.       if (y + dy > 100 || y + dy < 0) {
  18.         // Change the direction of the image
  19.         setDy(prevDy => -prevDy);
  20.       }
  21.  
  22.       // Update the position of the image
  23.       setX(prevX => prevX + dx);
  24.       setY(prevY => prevY + dy);
  25.     }, 100);
  26.  
  27.     return () => clearInterval(interval);
  28.   }, []);
  29.  
  30.   return (
  31.     <img
  32.       src="my-image.jpg"
  33.       style={{ position: 'absolute', left: x, top: y }}
  34.     />
  35.   );
  36. }
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement