@@ -19,6 +19,7 @@ export const ImageComparison = ({ image }: ImageComparisonProps) => {
1919 scale : 1 ,
2020 } ) ;
2121 const prevTransformStateRef = useRef ( transformState ) ;
22+ const imagesLoadedRef = useRef ( { lr : false , sr : false } ) ;
2223
2324 useEffect ( ( ) => {
2425 const prevTransformState = prevTransformStateRef . current ;
@@ -38,13 +39,69 @@ export const ImageComparison = ({ image }: ImageComparisonProps) => {
3839 } , [ transformState ] ) ;
3940
4041 useEffect ( ( ) => {
41- lrRef . current ?. centerView ( 1 , 0 ) ;
42- srRef . current ?. centerView ( 1 , 0 ) ;
42+ // Reset transform state when image changes
43+ setTransformState ( {
44+ positionX : 0 ,
45+ positionY : 0 ,
46+ scale : 1 ,
47+ } ) ;
48+ // Reset image load tracking
49+ imagesLoadedRef . current = { lr : false , sr : false } ;
4350 setHandlePosition ( 50 ) ;
4451 } , [ image ] ) ;
4552
53+ // Track image loading and center images once loaded
54+ useEffect ( ( ) => {
55+ // Center images function
56+ const centerImages = ( ) => {
57+ if ( lrRef . current && srRef . current ) {
58+ // Use requestAnimationFrame to ensure DOM is updated
59+ requestAnimationFrame ( ( ) => {
60+ lrRef . current ?. centerView ( 1 , 0 ) ;
61+ srRef . current ?. centerView ( 1 , 0 ) ;
62+ } ) ;
63+ }
64+ } ;
65+
66+ const lrImg = new Image ( ) ;
67+ const srImg = new Image ( ) ;
68+ let loadedCount = 0 ;
69+
70+ const checkAndCenter = ( ) => {
71+ loadedCount ++ ;
72+ if ( loadedCount === 2 ) {
73+ // Both images loaded, center them
74+ setTimeout ( ( ) => {
75+ centerImages ( ) ;
76+ } , 50 ) ; // Small delay to ensure DOM is ready
77+ }
78+ } ;
79+
80+ lrImg . onload = ( ) => {
81+ imagesLoadedRef . current . lr = true ;
82+ checkAndCenter ( ) ;
83+ } ;
84+ srImg . onload = ( ) => {
85+ imagesLoadedRef . current . sr = true ;
86+ checkAndCenter ( ) ;
87+ } ;
88+
89+ lrImg . src = image . LR ;
90+ srImg . src = image . SR ;
91+
92+ // Fallback: center after a timeout even if images don't load
93+ const fallbackTimer = setTimeout ( ( ) => {
94+ centerImages ( ) ;
95+ } , 500 ) ;
96+
97+ return ( ) => {
98+ clearTimeout ( fallbackTimer ) ;
99+ } ;
100+ } , [ image ] ) ;
101+
46102 return (
47103 < ReactCompareSlider
104+ key = { `${ image . LR } -${ image . SR } ` }
48105 onlyHandleDraggable
49106 className = "react-compare-slider w-full"
50107 handle = {
0 commit comments