Search code examples
javascriptjqueryhtmlcsssvg

svg to png not working, suspect svg element differences


Im having trouble figuring out why two different svg's would cause my javascript to work in one instance, but not in the other. I have only swapped out the svg elements in both examples, one works, one does not. Here is the code in two jsFiddles. The working example I got from here.

Ultimately, my goal is to save the current svg element of the floor plan, and insert the converted png as an inline img inside a rich text area. As if you took a cropped screenshot of the floor plan, and pasted it into a rich text area like you see in helpdesk sites. Im just having trouble converting to png.

Working: JsFiddle

Not Working: JsFiddle

Here is the js, i cant add the svg code or it will put me over the character limit of Stackoverflow.

    var svgString = new XMLSerializer().serializeToString(document.querySelector('#svg2'));

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var DOMURL = self.URL || self.webkitURL || self;
var img = new Image();
var svg = new Blob([svgString], {
  type: "image/svg+xml;charset=utf-8"
});
var url = DOMURL.createObjectURL(svg);
img.onload = function() {
  ctx.drawImage(img, 0, 0);
  var png = canvas.toDataURL("image/png");
  document.querySelector('#png-container').innerHTML = '<img src="' + png + '"/>';
  DOMURL.revokeObjectURL(png);
};
img.src = url;

Edit:

I have since settled on this code omitting the png/canvas conversions, and trying to place the serialized string of the svg, directly to the rich text area, but it gets an error in IE, Non-default namespace declarations must not have an empty URI. Line: 1, column142

var svgString = new XMLSerializer().serializeToString(document.querySelector('#svg2'));

var img = new Image();

var url = "data:image/svg+xml; charset=utf8, "+encodeURIComponent(svgString); 
img.onload = function() {

    document.querySelector('.ze_body').innerHTML = '<img src="'+url+'"/>';

};
img.src = url;

Also i think it would help if i showed more of the structure of how this rich text area currently sits. This is not our doing, its a product we use, and im just trying to get maps to paste into the description area so it can live with the ticket. Only access we have is js triggered from rules in the form. Screenshot of ze_body element as it stands in the DOM


Solution

  • It comes from your namespace declaration :

    Change

    xmlns:NS1="" NS1:xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:NS2="" NS2:xmlns:cc="http://creativecommons.org/ns#" xmlns:NS3="" NS3:xmlns:dc="http://purl.org/dc/elements/1.1/"
    

    to

    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/">
    

    and it should work.

    You can read about namespace declaration here.