Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { useState, useEffect } from 'react';
- function FloatingImage() {
- const [x, setX] = useState(0);
- const [y, setY] = useState(0);
- const [dx, setDx] = useState(1);
- const [dy, setDy] = useState(1);
- useEffect(() => {
- const interval = setInterval(() => {
- // Check if the image has reached the edge of the screen
- if (x + dx > 100 || x + dx < 0) {
- // Change the direction of the image
- setDx(prevDx => -prevDx);
- }
- if (y + dy > 100 || y + dy < 0) {
- // Change the direction of the image
- setDy(prevDy => -prevDy);
- }
- // Update the position of the image
- setX(prevX => prevX + dx);
- setY(prevY => prevY + dy);
- }, 100);
- return () => clearInterval(interval);
- }, []);
- return (
- <img
- src="my-image.jpg"
- style={{ position: 'absolute', left: x, top: y }}
- />
- );
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement