4

I currently have a problem. When wishes to convert a chart created with JOINTJS image, the elements do not display correctly ...

The diagram:

http://www.hostingpics.net/viewer.php?id=698706graph.png

Conversion :

http://www.hostingpics.net/viewer.php?id=867158graph2.png

Here is my code:

  var canvas = document.getElementById('canvas');
  var svg = document.querySelector('svg');
  var ctx = canvas.getContext('2d');
  var data = (new XMLSerializer()).serializeToString(svg);
  var DOMURL = window.URL || window.webkitURL || window;

  var img = new Image();
  var svgBlob = new Blob([data], {type: 'image/svg+xml;charset=utf-8'});
  var url = DOMURL.createObjectURL(svgBlob);

  img.onload = function () {
    ctx.drawImage(img, 0, 0);
    DOMURL.revokeObjectURL(url);

    var imgURI = canvas
        .toDataURL('image/png')
        .replace('image/png', 'image/octet-stream');

    triggerDownload(imgURI);
  };

  img.src = url;

After much research, different codes, I still can not find the solution. Thanks in advance !

Lucatorze
  • 107
  • 1
  • 9
  • This is because you can't load external resources from an svg inside an img element. You'll have to convert these to a dataURI and append it to your svg element. There are dupes, and this [doc topic](http://stackoverflow.com/documentation/html5-canvas/3689/media-types-and-the-canvas/14410/drawing-an-svg-image#t=201607270952095100516) – Kaiido Jul 27 '16 at 09:55
  • Here is one of the dupes : http://stackoverflow.com/questions/34042910/convert-svg-to-png-with-applied-images-as-background-to-svg-elements/34043188#34043188 not voting to close since you may have more issues than this. – Kaiido Jul 27 '16 at 10:02
  • Thank you very much ! I could adapt my code with this one ! – Lucatorze Jul 28 '16 at 06:54
  • Since you are using multiple time the same images, be sure to use the `` element and ro define only once your ``, otherwise your file will grow considerably in size (even if it stays in memory, it can have bad influences on low performance devices) – Kaiido Jul 28 '16 at 09:43

1 Answers1

3

Let me try to answer.

Use the below code to get SVG encoded data and store it in var (here 'encodedData')

var encodedData; 
var s = new XMLSerializer().serializeToString(document.getElementById("ur_svg_id"));
encodedData = window.btoa(s);

Simply draw the SVG Image to a canvas

var canvas = document.getElementById('canvas');
var ctx = c.getContext('2d');
ctx.drawSvg('data:image/svg+xml;base64,' + encodedData, 0, 0, 740, 1100);

Export the canvas to PNG image using filesaver.js

canvas.toBlob(function(blob) {
    saveAs(blob, "MyCanvas.png");
});

Make it simple !

Gokul Maha
  • 298
  • 8
  • 24