I am developing a drawing app, and now I want to add a function which creates SVG from my canvas or control points. (I save the mouse coordinates for each drawing step).
canvasElement.toDataURL("image/svg+xml"); // -- doesn't work
One condition - don't use external libs.
I understand, that it is possible to generate an SVG file in Javascript like:
var mysvg = "<svg>"; for(something) { mysvg += "something"; } //etc
But I don't think that it is good way.
Can you advise anything?
The first is to define the SVG with an img tag, then on the canvas grab that element and use the drawImage method. The second is to define an Image variable with src=”mySVG. svg”, and use drawImage on load. Important Note: This works well in Firefox, Chrome & IE, but it was not working on Opera or Android when I tried.
Any SVG image can be drawn with the Canvas API with enough effort.
I solved the problem by generating SVG file. I translated all my canvas drawing functions into SVG drawing tags.
Something like that:
function exportSVG() {
var svg = '<?xml version="1.0" standalone="yes"?>';
svg += '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">';
svg += '<svg width="1065px" height="529px" xmlns="http://www.w3.org/2000/svg" version="1.1">';
for(var i=0; i<myPoints.length; i++) {
svg += "M"+myPoints.x[i]+","+myPoints.y[i]+" ";
svg += "L"+myPoints.x[i+1]+","+myPoints.y[i+1];
svg += '" fill="none" stroke="rgb('+color+')" stroke-opacity="'+opacity+'" stroke-width="'+size+'px" stroke-linecap="round" stroke-linejoin="round" />';
}
svg += "</svg>";
}
So, in svg variable there will be SVG file generated from Canvas. Thanks everybody!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With