Flickering image in React when changing image (zooming, rotating, opacity)

83 Views Asked by At

I am trying to make a composite image GUI in React and trying to trying to rotate and zoom it until it fits the first image, as closely as possible. However, when changing the image, both images flicker.

import React, { useState, useEffect } from 'react';
import { Stage, Layer, Image as KonvaImage } from 'react-konva';

function App() {
  const [images, setImages] = useState({ image1: null, image2: null });
  const [anchor, setAnchor] = useState({ x: 700, y: 700 });
  const [rotation, setRotation] = useState(0);
  const [zoom, setZoom] = useState(1);
  const [opacity, setOpacity] = useState(1);

  useEffect(() => {
    const fetchImages = async () => {
      try {
        const response = await fetch('http://localhost:5000/get-images');
        if (response.ok) {
          const data = await response.json();
          setImages({
            image1: new window.Image(),
            image2: new window.Image(),
          });
          images.image1.src = `data:image/jpeg;base64,${data.image1}`;
          images.image2.src = `data:image/jpeg;base64,${data.image2}`;
        }
      } catch (error) {
        console.error("Error fetching images:", error);
      }
    };

    const intervalId = setInterval(fetchImages, 5000);

    return () => {
      clearInterval(intervalId);
    };
  }, [images]);

  return (
    <div className="App" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100vh' }}>
      <h1>Received Images</h1>
      <Stage width={1400} height={1400}>
        <Layer>
          <KonvaImage image={images.image1} x={700} y={700} />
          <KonvaImage 
            image={images.image2} 
            x={anchor.x} 
            y={anchor.y - images.image2?.height}
            rotation={rotation}
            scaleX={zoom}
            scaleY={zoom}
            opacity={opacity}
          />
        </Layer>
      </Stage>
      <div>
        <label>Rotation:</label>
        <input 
          type="range" 
          min="-180" 
          max="180" 
          value={rotation} 
          onChange={(e) => setRotation(parseFloat(e.target.value))} 
        />
      </div>
      <div>
        <label>Zoom:</label>
        <input 
          type="range" 
          min="0.5" 
          max="2" 
          step="0.1" 
          value={zoom} 
          onChange={(e) => setZoom(parseFloat(e.target.value))} 
        />
      </div>
      <div>
        <label>Opacity:</label>
        <input 
          type="range" 
          min="0" 
          max="1" 
          step="0.01" 
          value={opacity} 
          onChange={(e) => setOpacity(parseFloat(e.target.value))} 
        />
      </div>
    </div>
  );
}

export default App;

I have tried only redrawing one image, but even then the both images flicker, even though only image 2 is supposed to be redrawn.

0

There are 0 best solutions below