Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need to convert an HTML5 canvas to SVG for editing. How can I achieve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
437 views
Welcome To Ask or Share your Answers For Others

1 Answer

Try canvas2svg.js. [Demo]

I ran into needing this myself and ended up writing a library for this. At the time, the other libraries were a bit sparse, or didn't generate valid SVG.

The basic concept is the same though. You create a mock canvas 2D context and then generate an SVG scene graph as you call canvas drawing commands. Basically you can reuse the same drawing function. Depending on what context you pass to it, you either draw to a standard 2D canvas or generate an SVG document that you can serialize.

You can't actually "transform" a canvas element that's been drawn to, as it's just a bitmap, so keep that in mind. When you export to SVG you're really just calling the same drawing function again using a fake context.

So as a quick example:

//create a canvas2svg mock context
var myMockContext = new C2S(500,500); //pass in your desired SVG document width/height

var draw = function(ctx) {
    //do your normal drawing
    ctx.fillRect(0,0,200,200);
    //etc...
}

draw(myMockContext);
myMockContext.getSerializedSvg(); //returns the serialized SVG document
myMockContext.getSvg(); //inline svg

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...