我想将图表输出保存为图像,我使用Charts.js生成图形,以下代码适用于图形,但不适用于保存部分。
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.js"></script>
<script type="text/javascript" src="https://cdn.rawgit.com/eligrey/canvas-toBlob.js/master/canvas-toBlob.js"></script>
<script type="text/javascript" src="https://cdn.rawgit.com/eligrey/FileSaver.js/master/FileSaver.min.js"></script>
</head>
<body>
<canvas id="myChart" width="400" height="400"></canvas>
<br/><br/>
<button id="save-btn">Save Chart Image</button>
<script>
// Get the context of the canvas element we want to select
var data = [
{
value: 300,
color:"#F7464A",
highlight: "#FF5A5E",
label: "Red"
},
{
value: 50,
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Green"
},
{
value: 100,
color: "#FDB45C",
highlight: "#FFC870",
label: "Yellow"
},
{
value: 40,
color: "#949FB1",
highlight: "#A8B3C5",
label: "Grey"
},
{
value: 120,
color: "#4D5360",
highlight: "#616774",
label: "Dark Grey"
}
];
var ctx = document.getElementById("myChart").getContext("2d");
var myNewChart = new Chart(ctx).PolarArea(data);
$("#save-btn").click(function() {
$("#myChart").get(0).toBlob(function(blob) {
saveAs(blob, "chart_1");
});
});
</script>
</body>
</html>
这种方法是否正常,或者我应该使用其他方法,如base64或image2canvas等。 提前谢谢。
答案 0 :(得分:0)
你忘了添加jQuery。把它添加到头部!
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" integrity="sha384-3ceskX3iaEnIogmQchP8opvBy3Mi7Ce34nWjpBIwVTHfGYWQS9jwHDVRnpKKHJg7" crossorigin="anonymous"></script>