Note: There are no new demos added at this point and this site is in maintenance mode
start svg demo download
o10.5 ff3.6 cr5.0 sa5.0 ie9

Pointilizer

author: Erik Dahlström posted: August 22, 2010 at 06:00 PM categories: canvas, animation, raphaeljs view comments

This example shows a combination of html5 canvas and svg.

First, a raster image is processed by canvas and javascript to extract part of the pixel data as an array of points, relative size and color. The result is then passed to a small javascript function that uses the Raphaël framework to render the result, which in theory provides support all the way back to IE6. However, since the demo needs support for canvas to get any interesting results, you'll need at least IE9. The animation is done by the API provided by Raphaël, which is much less rich than what SVG in itself is. However, it shows that it's easy to animate vector graphics even in browsers that don't yet support SVG's declarative animation elements.

It's easy to extract the points data from raster images, it's wrapped into a utility function called sw.tools.pointilize which is provided by pointilizer.js. You provide an options array and a callback function. Here's an example of how it can look:

sw.tools.pointilize({
    url: "somephoto.jpg",
    output: "points", 
    points: 1000,
    threshold: 0, 
    width: 480,
    height: 360,
 },
 function(result) {
    // your callback function
    if (result.data)
    {
        // do something with the data
    }
});

The result.data that is passed back depends on the output format, if you pass "svg" instead it'll be a string that is the serialized svg image. The string can be inserted into the DOM by using DOMParser or element.innerHTML. DOMParser is supported by all browsers except IE, and parses a string into a DOM, it can handle both html and XML documents. The element.innerHTML setter which is defined in HTML5 is available on all browsers, but at the time of writing shows differences in how it handles XML input, and deployed older browsers will not handle the svg elements correctly. It's recommended to not rely on one single way, but instead gracefully fall back and handle such differences in the javascript code, testing for the functionality and not for a particular browser. Following that advise will provide you the best level of compatibility for your content.

Note that for the canvas data extraction to work you need to host the image and the script on the same domain, since the browsers generally throw a security exception if you try to read pixels from images that were from another domain.

Read and Post Comments