How to fix this flood fill code for html5 canvas
===

I am trying to turn all white (or close to white) pixels into transparent pixels, but I don't want it to include all white pixels, only the background white. If there is a white part of the image that's attached to the main image (like a tooth for example) then that should remain white, so it should be continuous (i.e. all attached to each other). it shouldn't go into the main image. 

I've tried to come up with my own function, but it's not working, does anyone see the problem?


This function basically creates a loop that goes around the boundary of the image so the 4 for loops in 'flood_fill_recursion' does that. Then for each one, I call a recursion function that does the flood fill. It checks if the current pixel is white, if so, it makes it transparent, if not then nothing happens. After it makes it transparent, it calls the function again with the 4 other pixels above, under, left and right of it.

	function flood_fill_recursion(image) {
		var canvas2 = document.createElement('canvas');
		var ctx = canvas2.getContext("2d");
		
		canvas2.width = image.width;
		canvas2.height = image.height;
		
		ctx.drawImage(image,0,0);

		var imgd = ctx.getImageData(0, 0, canvas2.width, canvas2.height);
		var pix = imgd.data;

		var x, y;
		for(var i=0; i<canvas2.width; i++) {
			x = i;
			y = 0;
			flood_fill_recursion_helper(pix, canvas2, get_index(x,y), x, y);
		}
		for(var i=1; i<canvas2.height; i++) {
			x = canvas2.width-1;
			y = i;
			flood_fill_recursion_helper(pix, canvas2, get_index(x,y), x, y);
		}
		for(var i=canvas2.width-2; i>=0; i--) {
			x = i;
			y = canvas2.height-1;
			flood_fill_recursion_helper(pix, canvas2, get_index(x,y), x, y);
		}
		for(var i=canvas2.height-2; i>0; i--) {
			x = 0;
			y = i;
			flood_fill_recursion_helper(pix, canvas2, get_index(x,y), x, y);
		}

		ctx.putImageData(imgd, 0, 0);
		return canvas2.toDataURL();
	}
	function get_index(x, y, width) {
		return 4*x + width*y;
	}
	function is_white(r, g, b) {
		return r >= 230 && g >= 230 && b >= 230;
	}
	function flood_fill_recursion_helper(pix, canvas2, index, x, y) {
		if (x < 0 || y < 0 || x >= canvas2.width || y >= canvas2.height) {
		} else if (is_white(pix[index], pix[index+1], pix[index+2])) {
			pix[index] = 0;
			pix[index+1] = 0;
			pix[index+2] = 0;
			pix[index+3] = 0;
			var nx, ny;
			nx = x - 1; ny = y;
			flood_fill_recursion_helper(pix, canvas2, get_index(nx,ny), nx, ny);
			nx = x + 1; ny = y;
			flood_fill_recursion_helper(pix, canvas2, get_index(nx,ny), nx, ny);
			nx = x; ny = y - 1;
			flood_fill_recursion_helper(pix, canvas2, get_index(nx,ny), nx, ny);
			nx = x; ny = y + 1;
			flood_fill_recursion_helper(pix, canvas2, get_index(nx,ny), nx, ny);
		}
	}