我正在尝试在chart.js中使用变量。我尝试输入到图表中的数据每隔几周就会更改一次,我真的不想手动进行此操作。
有人知道我该怎么做吗?我搜索了其他解决方案,找不到任何解决方案。
我以前从未做过,所以任何提示都会很棒。
<html>
<head>
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script> -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0/dist/Chart.min.js"></script>
</head>
<div id="totals">
<span id="totalOne">$12.64</span>
<span id="totalTwo">$300.65</span>
</div>
<div class="chart">
<canvas id="myChart" width="50" height="50"></canvas>
</div>
</html>
<script>
$(document).ready(function(){
var ctx = document.getElementById('myChart').getContext('2d');
var totalCosts = Number($("#totalOne").html());
console.log(typeof totalCosts);
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ['total costs', 'total income'],
datasets: [{
label: '# of Votes',
data: [totalCosts, 12.76],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
});
</script>
如果您可以获取#totalOne和#totalTwo的值并在图表中显示它们,我会很高兴
谢谢