使用canvas2svg.js将chart.js图表导出到SVG

oknrviil  于 2022-11-23  发布在  Chart.js
关注(0)|答案(4)|浏览(271)

我正在尝试使用canvas2svg.jschart.js图表导出到SVG。
它似乎不起作用,因为chart.js拒绝使用canvas2svg.js创建的“假”画布

我的HTML代码:

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

我的脚本:

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"

我已经在Codepen上发布了完整的例子(抱歉,这里有很长的js,我找不到导入canvas2svg的链接,所以我把它粘贴在脚本的开头。)

kqlmhetl

kqlmhetl1#

如果您使用的是Chart.JS的最新版本(在撰写本文时为2.7.1),您可以通过稍微调整canvas2svg来运行它。看一看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:**仅当禁用图表的动画和响应(设置为false)时才有效。

wf82jlnq

wf82jlnq2#

如果有人遇到这个问题,替换sspechts中的ctx,并禁用graphdata的动画和响应,可以从画布中获取svg。我派生了codepen项目,并添加了一个函数,使用sspecht中的codesnippet和两个标志来调整库:

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

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

alen0pnh

alen0pnh3#

对于devicePixelRatio不为1或放大/缩小的设备,我执行了以下操作:

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

否则SVG可能会被裁剪。

izkcnapc

izkcnapc4#

最新版本的Chart.js(3.9.1)似乎使用了setTransform()和resetTransform()方法,Canvas2SVG没有实现这些方法(github上大约5年没有更新)。
此维护版本确实实现了这些方法:(x)的值。
然而,它似乎在画线方面有问题。我为此写了一个小的解决方法(参见https://github.com/zenozeng/svgcanvas/issues/25)。
希望能帮上忙。

相关问题