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.)
If you use a recent Chart.JS version (2.7.1 at time of writing) you can get this running by tweaking canvas2svg a bit. I added the following code to canvas2svg: Have a look at the Codepen
ctx.prototype.getContext = function (contextId) {
if (contextId=="2d" || contextId=="2D") {
return this;
}
return null;
}
ctx.prototype.style = function () {
return this.__canvas.style
}
ctx.prototype.getAttribute = function (name) {
return this[name];
}
ctx.prototype.addEventListener = function(type, listener, eventListenerOptions) {
console.log("canvas2svg.addEventListener() not implemented.")
}
BUT: It only works if you disable animation and responsiveness of the chart (set to false).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With