Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting chart.js charts to svg using canvas2svg.js

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.)

like image 252
bocko Avatar asked Aug 08 '17 08:08

bocko


1 Answers

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).

like image 70
sspecht Avatar answered Sep 21 '22 07:09

sspecht