gliffy / canvas2svg

Translates HTML5 Canvas draw commands to SVG
MIT License
693 stars 157 forks source link
html5-canvas javascript node-canvas nodejs svg

Canvas2Svg Build Status

This library turns your Canvas into SVG using javascript. In other words, this library lets you build an SVG document using the canvas api. Why use it?

Demo

http://gliffy.github.io/canvas2svg/

How it works

We create a mock 2d canvas context. Use the canvas context like you would on a normal canvas. As you call methods, we build up a scene graph in SVG. Yay!

Usage

//Create a new mock canvas context. Pass in your desired width and height for your svg document.
var ctx = new C2S(500,500);

//draw your canvas like you would normally
ctx.fillStyle="red";
ctx.fillRect(100,100,100,100);
//etc...

//serialize your SVG
var mySerializedSVG = ctx.getSerializedSvg(); //true here, if you need to convert named to numbered entities.

//If you really need to you can access the shadow inline SVG created by calling:
var svg = ctx.getSvg();

Tests

To run tests:

npm install
npm test

To run tests against Chrome and Firefox, call karma directly. This is not the default npm test due to the limited browser selection in travis.

npm install karma-cli -g
karma start

Debug

Play with canvas2svg in the provided test/playground.html or run test locally in your browser in test/testrunner.html

Add An Example Case

Add a test file to the test/example folder. In your file make sure to add the drawing function to the global C2S_EXAMPLES, with your filename as a key. For example test\example\linewidth.js should look something like:

window.C2S_EXAMPLES['linewidth'] = function(ctx) {
    for (var i = 0; i < 10; i++){
        ctx.lineWidth = 1+i;
        ctx.beginPath();
        ctx.moveTo(5+i*14,5);
        ctx.lineTo(5+i*14,140);
        ctx.stroke();
    }
};

install gulp globally if you haven't done so already

npm install -g gulp

Then run the following to update playground.html and testrunner.html

gulp

You should now be able to select your new example from playground.html or see it run in testrunner.html

If you find a bug, or want to add functionality, please add a new test case and include it with your pull request.

Using with node.js

You can use canvas2svg with node.js using jsdom with node-canvas. To do this first create a new document object, and then create a new instance of C2S based on that document:

var canvas = require('canvas'),
    jsdom = require('jsdom'),
    C2S = require('canvas2svg');

var document = jsdom.jsdom();
var ctx = new C2S({document: document});

// ... drawing code goes here ...

N.B. You may not need node-canvas for some simple operations when using jsdom >= 6.3.0, but it's still recommended that you install it.

Updates

Misc

Some canvas 2d context methods are not implemented yet. Watch out for setTransform and arcTo.

Releasing

To release a new version:

License

This library is licensed under the MIT license.