我试图让用户下载SVG图片为PNG。 您可以通过JSFIDDLE
访问代码SVG到CANVAS部分无效。
已经添加了canvg和Mozillas的代码,他们都没有工作。还添加了Canvas2Image,如果canvas具有元素,它应该有效。
答案 0 :(得分:4)
感谢gabelerner开发的canvg帮助我解决了这个问题
以下是您可能想要的示例SVG和JS部分
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));
}
} );
答案 1 :(得分:0)
尝试使用fabric.js将SVG转换为画布(此处为demo,当您单击侧边栏中的按钮时,svg将实时转换为画布)。
Fabric不支持所有SVG功能,但它适用于简单的情况。
以下是使用loadSVGFromURL
。
1)你需要&lt; canvas&gt;元素:
<canvas id="my-canvas"></canvas>
2)从画布中初始化fabric.Element
:
var canvas = new fabric.Element('my-canvas');
3)通过XHR获取SVG:
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);
});