Reputation: 9420
I'm trying to let user download SVG graphic as PNG. You may reach the code via JSFIDDLE
SVG to CANVAS part is not working.
Already added canvg and Mozillas's code neither of them working. Also added Canvas2Image which should works if canvas has element.
Upvotes: 5
Views: 2406
Reputation: 9420
Thanks to gabelerner who developed canvg helped me to fix it
Here is the sample SVG and JS part you may want to have
var svg_XML_NoSpace = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="1024" height="768"><desc>Created with Raphaël</desc><defs></defs><image x="0" y="0" width="1024" height="768" preserveaspectratio="none" xlink:href="http://<mydomain>/<myfolder>/<myfile>"></image><path fill="none" stroke="#ff0000" d="M414,114L722,114" style="stroke-width: 3px;" stroke-width="3"></path></svg>'; //based on gabelerner
//add canvas into body
var canvasID = "myCanvas";
var canvas = document.createElement('canvas');
canvas.id = canvasID;
document.body.appendChild(canvas);
//convert svg to canvas
canvg(document.getElementById(canvasID), svg_XML_NoSpace, {
ignoreMouse: true, ignoreAnimation: true,
renderCallback: function () {
//save canvas as image
Canvas2Image.saveAsPNG(document.getElementById(canvasID));
}
} );
Upvotes: 4
Reputation: 39168
Try converting SVG to canvas with fabric.js (here's a demo, in which svg is converted to canvas in real time, when you click on a button in sidebar).
Fabric doesn't support all SVG features but it should work for simple cases.
Here's an example of using loadSVGFromURL
.
1) You'll need to have <canvas> element:
<canvas id="my-canvas"></canvas>
2) Initialize fabric.Element
out of the canvas:
var canvas = new fabric.Element('my-canvas');
3) Fetch SVG via XHR:
canvas.loadSVGFromURL('path_to_your_shape.svg', function(objects, options) {
// `objects` is now an array of fabric objects representing
// svg shapes from the document
// if it's one shape, we'll just work with that
// if it's more than one — we'll create a unified group out of it,
// using `fabric.PathGroup`
var loadedObject = objects.length > 1
? new fabric.PathGroup(objects, options)
: objects[0];
// we can now change object's properties like left, top, angle, opacity, etc.
// this is not necessary, of course
loadedObject.set({
left: 123,
top: 321,
angle: 55,
opacity: 0.3
});
// and add it to canvas
canvas.add(loadedObject);
});
Upvotes: 0