Menu

Cutting out a background colour with a canvas pixel loop: what I learned building Color to Transparent
📰

Cutting out a background colour with a canvas pixel loop: what I learned building Color to Transparent

DEV Community: frontend·Nathan Cole·16 days ago
#d6PHZF4R
#devtofrontend#devto#dev#tolerance#background
Long article (736 words) — no AI summary yet.
Reading 0:00
15s threshold

A few months ago I needed one boring thing: a logo on a white background that had to sit on a transparent one. Every online tool I found wanted an account, a watermark, or an upload of a file I would rather not send anywhere. So I wrote the loop myself, and it turned into Color to Transparent , a free browser tool that removes one chosen colour from an image and makes it transparent.

The core is shorter than you think

Every pixel is four numbers in a Uint8ClampedArray . Once you have the background colour you want gone, the rest is a distance check:

function keyOut ( ctx , width , height , target , tolerance ) { const img = ctx . getImageData ( 0 , 0 , width , height ) ; const d = img . data ; const [ tr , tg , tb ] = target ; const limit = tolerance * tolerance * 3 ;

for ( let i = 0 ; i < d . length ; i += 4 ) { const dr = d [ i ] - tr , dg = d [ i + 1 ] - tg , db = d [ i + 2 ] - tb ; if ( dr * dr + dg * dg + db * db <= limit ) d [ i + 3 ] = 0 ; } ctx .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.