Robin Berjon

For Whom The Belle Trolls

Gluing Vectors

Canvas-SVG Bridge

This library can do two things: capture a snapshot of a canvas element and return it as SVG, and provide a direct canvas API that produces live SVG output.

There are two classes you need to care about: CanvasSVG.Deferred and CanvasSVG.Live. The former allows you to run a canvas script and at a given point ask for a snapshot of where it's at as SVG. It has a lesser impact on performance as all it does while canvas is running is keep a history of the commands that were invoked, all its serious processing taking place when you ask for the SVG to be generated. The latter provides you with an SVG element that is updated in real time to match what is being done to the canvas.

The source code is available from its Google Code project, and patches are welcome.

Using them is straightforward. For CanvasSVG.Deferred:

var cs = new CanvasSVG.Deferred();
var canvas = document.getElementById('your-canvas');
cs.wrapCanvas(canvas);
var context = canvas.getContext('2d');
// ... canvas code against context here ...

And for CanvasSVG.Live:

var cs = new CanvasSVG.Live();
var canvas = document.getElementById('your-canvas');
cs.wrapCanvas(canvas);
var context = canvas.getContext('2d');
ctx.setParent(document.getElementById('parent-of-the-svg'));
// ... canvas code against context here ...

It's not complete, but should be roughly usable. I haven't tested it excessively and it's missing some useful parts such as images, gradients, or patterns. That being said, it pretty much works and if you're interested I encourage you to give it a shot. You can see it in action on this test page (toggle between static and live tests with the buttons at the top, then run tests by clicking on the left). One interesting aspect is that there are some parts of the canvas specification that it appears to run better than browsers (notably transforms).

You can download it here. A more detailed list of issues is at the top. This is distributed under the Artistic License 2.0. Use at your own risk. This is produced by myself and not as part of my consulting contract with Vodafone.