gpt4 book ai didi

javascript - 将 Canvas 导出到 SVG 文件

转载 作者:行者123 更新时间:2023-12-05 06:16:00 29 4
gpt4 key购买 nike

我正在尝试将包含使用 Chart.js 创建的图表的 Canvas 转换为 SVG,以便能够从包含图表的页面下载 SVG 文件。我已经谷歌搜索了 5 个小时,我尝试了多个脚本,我得到的最好的脚本是 this one但问题是转换后的 SVG 仅包含图表的四分之一,我认为这与 Chart.js 的响应选项有关(为了转换为 SVG,该选项应该为 false)。

这是 HTML 文件。

<html>
<body>
<div class="chartContainer">
<canvas id="radarCanvas" style="height: 600px;width: 600px;"></canvas>
</div>
<a id="down">
<button type="button" onclick="download()">Download</button>
</a>
</body>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.js"></script>
<script type="text/javascript" src="canvas2svg.js"></script>
<script type="text/javascript">
var graphData = {
type: 'pie',
data: {
labels: ["Africa", "Asia", "Europe", "Latin America", "North America"],
datasets: [{
label: "Population (millions)",
backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
data: [2478,5267,734,784,433]
}]
},
options: {
title: {
display: true,
text: 'Predicted world population (millions) in 2050'
},
animation: false,
responsive:false,
maintainAspectRatio: false
}
}


function tweakLib(){
C2S.prototype.getContext = function (contextId) {
if (contextId=="2d" || contextId=="2D") {
return this;
}
return null;
}

C2S.prototype.style = function () {
return this.__canvas.style
}

C2S.prototype.getAttribute = function (name) {
return this[name];
}

C2S.prototype.addEventListener = function(type, listener, eventListenerOptions) {
console.log("canvas2svg.addEventListener() not implemented.")
}
}


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

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

tweakLib();
// deactivate responsiveness and animation

// canvas2svg 'mock' context
var svgContext = C2S(600,600);

// new chart on 'mock' context fails:
var mySvg = new Chart(svgContext, graphData);
console.log(svgContext.getSvg());
function download() {
var dl = document.createElement("a");
document.body.appendChild(dl); // This line makes it work in Firefox.
var svg= svgContext.getSvg();
if (window.ActiveXObject) {
svgString = svg.xml;
} else {
var oSerializer = new XMLSerializer();
svgString = oSerializer.serializeToString(svg);
}
dl.download = "Chart.svg";
// return "data:image/svg+xml," + encodeURIComponent(svgAsXML);
dl.href='data:image/svg+xml;utf8,' + encodeURIComponent(svgString);
dl.click();
}

</script>

</html>

最佳答案

愚蠢的我.....所有需要添加的是......

mySvg.width=600;
mySvg.height=600;
//or any size

这些行需要在这些之后,图表是在 C2S 对象上创建的

...
// deactivate responsiveness and animation

// canvas2svg 'mock' context
var svgContext = C2S(600,600);

// new chart on 'mock' context fails:

var mySvg = new Chart(svgContext, graphData);
// insert here

关于javascript - 将 Canvas 导出到 SVG 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62249315/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com