Thursday, September 18th, 2008

Sandbag text flow with Canvas

Category: Canvas

Jacob Seidelin has implemented Sandbag text wrapping with Canvas allowing the text to flow nicely around an object:

With CSS you can make text wrap around an image using the float property and for most purposes this is quite adequate. However, it doesn’t take into account the actual image and treats it as one big block, even if you’d prefer the text to wrap around the actual content in the picture, magazine style.

Along came a technique called sandbag DIVs (first published by Rob Swan a few years ago, I believe) that solved the problem for those odd cases where you need something fancier than float:left. The idea is to build a structure of virtual “sandbags” out of DIV elements and then let the text flow around those instead of the image. This can be done either manually for each image or with a serverside script as shown in the ALA article.

Since we now have pixel access (in cool browsers, anyway) via the Canvas element, this technique can now be implemented dynamically with a bit of JavaScript.The approach is very similar to the one at ALA, in that we scan from either left or right looking for the first solid pixel and then use that information to create a bunch of DIVs of suitable dimensions, only we’re doing it client side with JS. These DIVs are then styled with the original image as a background image, positioned to make it all appear as one whole image.

Using the small script linked below you simply give your image a CSS class of either “sandbag-left” or “sandbag-right”, depending on how your image should float. If the browser does not support Canvas and image data access, a fallback mechanism simply sets the CSS float property to “left” or “right”, degrading to the old rectangular text wrap.

Posted by Dion Almaer at 7:37 am
5 Comments

+++--
3.2 rating from 22 votes

5 Comments »

Comments feed TrackBack URI

Neat idea. First time you hit it, it seems rather slow. And the page is rather distorted.

I think the div method is still better with performance, plus no JavaScript is needed.

Comment by epascarello — September 18, 2008

Looks great and rendered fast for me on FF3 Mac.

Comment by dshaw — September 18, 2008

Interesting…if by “cool browsers” you mean “it only works in Firefox”.

This fails in Safari, Chrome, and IE7 on the PC.

Comment by commadelimited — September 19, 2008

Interesting.. that’s almost exactly what is pointed out in the article.

@kae: Nice! Although the point here was to do it all on the client-side.

Comment by jseidelin — September 19, 2008

commadelimited: Firefox and Opera. ;)

Comment by p01 — September 21, 2008

Leave a comment

You must be logged in to post a comment.