
[英]In browser conversion of svg to png image (cross browser including IE)
[英]SVG with pattern and image element conversion to PNG Image failed
我试图将用Raphael.js生成的svg转换成PNG图像。 好吧,当svg没有模式和图像组件时,我将svg转换为图像。 然后当我将这两个组件添加到SVG中时出现问题并且转换失败。 完整的小提琴在 这里 。 即使我保存生成的svg并在浏览器中打开而不转换为图像,也不会渲染图像和模式。
代码段是:
var r = Raphael(document.getElementById("cus"), 390, 253);
r.setViewBox(-5, -2, 228, 306);
for (var outline in doorMatOutline) {
var path = r.path(doorMatOutline[outline].path);
//path.attr({fill: 'url('+patternuri+')'}); //adding pattern
}
//adding image
var img = r.image(imageuri, 5 ,10 ,100 ,100);
var svg = $('#cus').html().replace(/>\s+/g, ">").replace(/\s+</g, "<");
canvg('cvs', svg, {
ignoreMouse: true,
ignoreAnimation: true
});
var canvas = document.getElementById('cvs');
var img = canvas.toDataURL("image/png");
$("#resImg").attr('src', img);
$("#cus").hide();
我在http://jsfiddle.net/fktGL/1/解决了这个问题,首先我必须更改svg属性
xmlns="http://www.w3.org/2000/svg"
至
xmlns:xlink="http://www.w3.org/1999/xlink"
因为svg没有在W3C验证服务上验证, 这里是一个stackoverflow,解释了需要进行更改。
然后,我必须添加一些超时以允许SVG正确呈现。 我理解这是因为图像已经在SVG和画布中绘制,但两者都需要一些时间来渲染图像。 我的解决方案我不能在较慢的设备上完美工作(增加超时会有所帮助),但我不知道另一种解决方法(欢迎任何评论/改进)。
这是最后的片断
var r = Raphael(document.getElementById("cus"), 390, 253);
r.setViewBox(-5, -2, 228, 306);
for (var outline in doorMatOutline) {
var path = r.path(doorMatOutline[outline].path);
path.attr({
fill: 'url(' + patternuri + ')'
});
}
$('#cus svg').removeAttr('xmlns');
// If not IE
if(/*@cc_on!@*/false){
$('#cus svg').attr('xmlns:xlink',"http://www.w3.org/1999/xlink");
}
// First timeout needed to render svg (I think)
setTimeout(function(){
var svg = $('#cus').html();
window.svg = svg;
canvg(document.getElementById('cvs'), svg);
// annother delay required after canvg
setTimeout(function(){
var canvas = document.getElementById('cvs'),
img = canvas.toDataURL("image/png");
$("#resImg").attr('src', img);
//$("#cus").hide();
console.log("ending... ");
},100)
},100);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.