Flood Filling In A Canvas

Wednesday, November 21, 2012

Canvasfill is a demo for a friend who wants to flood fill a clicked area in an HTML 5 canvas.

A couple notes:

JavaScript loads a PNG image into the canvas when the page loads.

var img = new Image();
img.onload = function () {
canvas.width = img.width;
canvas.height = img.height;
img.src = "thermometer_01.png";

The image and the JavaScript must load from the same domain for the sample to work, otherwise you’ll run into security exceptions (unless you try to CORS enable the image, which doesn’t work everywhere).

The code uses a requestAnimationFrame polyfill from Paul Irish for efficient animations.

The code uses getImageData and putImageData to get and color a single pixel on each iteration.

image = context.getImageData(point.x, point.y, 1, 1);
var pixel = image.data;

This is not the most efficient approach to using the canvas, so if you need speed you’ll want to look at grabbing the entire array of pixels. With the current approach it is easier to “see” how the flood fill algorithm works since you can watch as pixels change colors in specific directions.

The flood fill algorithm itself is an extremely primitive queue-based (non-recursive) algorithm. It doesn’t deal well with anti-aliased images, for example, so you might need to look at more advanced algorithms if the image is not a blocky clip art image or a screen shot of Visual Studio 2012 with the default color scheme.

gravatar Dan Wednesday, November 21, 2012
Heh, it would be smart to disable clicks while in the process of filling. If you double click in a space it gets caught up in a loop.

It's even possible to flood fill the flood fill while it's filling ;)
gravatar Scott Allen Wednesday, November 21, 2012
@Dan - yeah, I noticed that. :)
gravatar Stone Thursday, November 22, 2012
Hmmm - doesn't seem to work in Firefox.
Comments are now closed.
My Pluralsight Courses
The Podcast!