有一些问题让下面的工作。我不确定它的前夕是否可以阅读一些关于在charts.js中重新创建图表的帖子,但不确定这里是否需要这些。将值从函数传递给donutData变量的简单示例。
<!doctype html>
<html>
<head>
<title>Doughnut Chart</title>
<script src="../Chart.js"></script>
<style>
body{
padding: 0;
margin: 0;
}
#canvas-holder{
width:30%;
}
</style>
</head>
<body>
<div id="canvas-holder">
<canvas id="chart-area" width="500" height="500"/>
</div>
<div id="demo">dd</div>
<button onclick="myFunction(20,30,50)">Click me</button>
<script>
var doughnutData = {};
function myFunction(a,b,c)
{
var item1 = parseInt(a);
var item2 = parseInt(b);
var item3 = parseInt(c);
var total = item1 + item2 + item3;
var ITEM1PERCENT = (item1 / total) * 100;
var ITEM2PERCENT = (item2 / total) * 100;
var ITEM3PERCENT = (item3 / total) * 100;
if(isNaN(ITEM1PERCENT)) {
var ITEM1PERCENT = 0;
}
if(isNaN(ITEM2PERCENT)) {
var ITEM2PERCENT = 0;
}
if(isNaN(ITEM3PERCENT)) {
var ITEM3PERCENT = 0;
}
var doughnutData = [
{
value: ITEM1PERCENT.toFixed(2),
color:"#F7464A",
highlight: "#FF5A5E",
label: "Red"
},
{
value: ITEM2PERCENT.toFixed(2),
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Green"
},
{
value: ITEM3PERCENT.toFixed(2),
color: "#FDB45C",
highlight: "#FFC870",
label: "Yellow"
}
];
loadFunction();
document.getElementById("demo").innerHTML = doughnutData;
}
function loadFunction()
{
var ctx = document.getElementById("chart-area").getContext("2d");
window.myDoughnut = new Chart(ctx).Doughnut(doughnutData, {responsive : true});
}
window.onload = function(){
var ctx = document.getElementById("chart-area").getContext("2d");
window.myDoughnut = new Chart(ctx).Doughnut(doughnutData, {responsive : true});
};
myFunction(1,2,3);
</script>
</body>
</html>
任何指示或帮助表示赞赏。
答案 0 :(得分:0)
您正在使用&#34; var doughnutData&#34;在myFunction(..)中定义局部变量doughnutData。删除&#34; var&#34;并使其成为全球性的。
doughnutData = [
{
value: ITEM1PERCENT.toFixed(2),
color:"#F7464A",
highlight: "#FF5A5E",
label: "Red"
},
{
value: ITEM2PERCENT.toFixed(2),
color: "#46BFBD",
highlight: "#5AD3D1",
label: "Green"
},
{
value: ITEM3PERCENT.toFixed(2),
color: "#FDB45C",
highlight: "#FFC870",
label: "Yellow"
}
];