SVG with pattern and image element conversion to PNG Image failed
I am trying to covert svg generated with Raphael.js into PNG image. Well, I converted the svg into image when svg has no pattern and image component. Then again when I add these two component into SVG something goes wrong and conversion fails. Complete fiddle is here. Even if I save the generated svg and open in browser without conversion to image the image and patter is not rendered.
The code snippet is :
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();
I have solved this here http://jsfiddle.net/fktGL/1/, first I had to change the svg attribute from
xmlns="http://www.w3.org/2000/svg"
to
xmlns:xlink="http://www.w3.org/1999/xlink"
as the svg wasn't validating on the W3C validation service and here is a stackoverflow explaining that a change is required.
I then had to add some timeouts to allow the SVG to render properly. I understand this is because the image has been drawn in the SVG & canvas but both need some time to render the image. My solution my not work perfectly on slower devices( an increase in the timeouts would help), but I don't know another way to get around this (welcome any comments/improvements).
Here is the final snipit
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);
链接地址: http://www.djcxy.com/p/13538.html
上一篇: 贝宝费用链接或平行付款