OdeToCode IC Logo

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.