I'm working on a React component that receives an imageUrl
and visualizes it on a canvas. The component intentionally adds a 2-second delay to simulate loading time for large images. However, I'm facing an issue: when the imageUrl
changes in the parent component and while the image is loading, the previous image disappears from the browser momentarily then the new image is shown, causing a flicker effect. The behavior I am looking for is the component keeps showing the previous image until the new image is fully loaded and the swaps them.
How can I modify my existing code to ensure that the transition between images is smooth without any flicker?Here's my current implementation:
class ImageViewer extends React.Component { constructor(props) { super(props); this.imagecanvas = React.createRef(); } componentDidMount() { this.drawCanvas(); } componentDidUpdate(prevProps) { if (prevProps.imageUrl !== this.props.imageUrl) { this.drawCanvas(); } } drawCanvas() { const canvas = this.imagecanvas.current; const context = canvas.getContext('2d'); const image = new Image(); // Clearing previous image context.clearRect(0, 0, canvas.width, canvas.height); // Load new image image.onload = () => { setTimeout(() => { context.drawImage(image, 0, 0); }, 2000); }; image.src = this.props.imageUrl; } render() { return (<canvas id="imageView" ref={this.imagecanvas}></canvas> ); }}
Any suggestions or improvements to prevent the flicker during image loading would be greatly appreciated!
I have searched the internet and found the structure provided above is very common, however, I have not seen any mention of the flickering issue and how to address it.