Exporting chart.js charts to svg using canvas2svg.js

Viewed 12786

I am trying to export chart.js chart to svg using canvas2svg.js.

It does not seems to be working, since chart.js refuses to use 'fake' canvas created by canvas2svg.js

My HTML code:

<div style="position: relative; height:20vh; width:100vh">
<canvas id="radarCanvas" ></canvas>
</div>

My script:

var ctx = document.getElementById("radarCanvas").getContext("2d");

var radarChart = new Chart(ctx, graphData);  // Works fine


// Create canvas2svg 'fake' context
var c2s = C2S(500,500);

// new chart on 'fake' context fails:
var mySvg = new Chart(c2s, graphData);
// Result (console):
// "Failed to create chart: can't acquire context from the given item"

I've posted full example on Codepen (Sorry for long js there, I could not find a link from which to import canvas2svg so I pasted it at the beginnning of the script.)

3 Answers

In case somebody stumbles across this question, replacing the ctx in sspechts answer to C2S and disabling animation and responsiveness of the graphdata one can get the svg from the canvas. I forked the codepen project and added one function which tweaks the library with the codesnippets from sspecht and the two flags:

// deactivate responsiveness and animation
graphData.options.responsive = false;
graphData.options.animation = false;

https://codepen.io/anon/pen/RYVVPY

For devices that have a devicePixelRatio different than 1 or are zoomed in/out I did:

const getDevicePixelRatio = window.devicePixelRatio
window.devicePixelRatio = 1;
// C2S Code
window.devicePixelRatio = getDevicePixelRatio

Otherwise the svg may get cropped.

Related