@@ -55,52 +55,47 @@ function pathToFrame(framePath) {
5555}
5656
5757function findFrame ( image ) {
58- const middleX = parseInt ( image . bitmap . width / 2 , 10 ) ;
59- const middleY = parseInt ( image . bitmap . height / 2 , 10 ) ;
60-
61- let left ;
62- let right ;
63- let top ;
64- let bottom ;
65-
66- // Scan left
67- for ( let i = middleX ; i >= 0 ; i -- ) {
68- const idx = image . getPixelIndex ( i , middleY ) ;
69- const alpha = image . bitmap . data [ idx + 3 ] ;
70- // console.log('i', i, middleY, alpha);
71- if ( alpha === 255 ) {
72- left = i ;
73- break ;
74- }
75- }
58+ const { width, height } = image . bitmap ;
7659
77- // Scan right
78- for ( let i = middleX ; i <= image . bitmap . width ; i ++ ) {
79- const idx = image . getPixelIndex ( i , middleY ) ;
80- const alpha = image . bitmap . data [ idx + 3 ] ;
81- if ( alpha === 255 ) {
82- right = i ;
83- break ;
84- }
85- }
60+ const offsets = [ [ 1 , 0 ] , [ - 1 , 0 ] , [ 0 , 1 ] , [ 0 , - 1 ] ] ;
8661
87- // Scan top
88- for ( let i = middleY ; i >= 0 ; i -- ) {
89- const idx = image . getPixelIndex ( middleX , i ) ;
90- const alpha = image . bitmap . data [ idx + 3 ] ;
91- if ( alpha === 255 ) {
92- top = i ;
93- break ;
94- }
95- }
62+ const s = 12 ;
63+ const mask = ( 1 << s ) - 1 ;
64+ const xyToPosition = ( x , y ) => ( ( x & mask ) << s ) + ( y & mask ) ;
65+ const positionToXy = p => {
66+ const y = p & mask ;
67+ const x = p >> s ;
68+ return [ x , y ] ;
69+ } ;
70+
71+ const middleX = Math . floor ( width / 2 ) ;
72+ const middleY = Math . floor ( height / 2 ) ;
73+
74+ let top = middleY ;
75+ let left = middleX ;
76+ let bottom = middleY ;
77+ let right = middleX ;
78+
79+ const floodFill = new Set ( [ xyToPosition ( middleX , middleY ) ] ) ;
80+
81+ for ( const p of floodFill ) {
82+ const [ px , py ] = positionToXy ( p ) ;
83+ for ( const [ dx , dy ] of offsets ) {
84+ const x = px + dx ;
85+ const y = py + dy ;
86+
87+ if ( ! ( x >= 0 && y >= 0 && x <= width && y <= height ) ) continue ;
88+
89+ const index = image . getPixelIndex ( x , y ) ;
90+ const alpha = image . bitmap . data [ index + 3 ] ;
91+
92+ if ( alpha === 255 ) continue ;
9693
97- // Scan bottom
98- for ( let i = middleY ; i <= image . bitmap . height ; i ++ ) {
99- const idx = image . getPixelIndex ( middleX , i ) ;
100- const alpha = image . bitmap . data [ idx + 3 ] ;
101- if ( alpha === 255 ) {
102- bottom = i ;
103- break ;
94+ floodFill . add ( xyToPosition ( x , y ) ) ;
95+ top = Math . min ( y , top ) ;
96+ left = Math . min ( x , left ) ;
97+ bottom = Math . max ( y + 1 , bottom ) ;
98+ right = Math . max ( x + 1 , right ) ;
10499 }
105100 }
106101
0 commit comments