gpt4 book ai didi

javascript - ChartJS 根据下拉选择更改图表

转载 作者:行者123 更新时间:2023-11-29 18:03:26 25 4
gpt4 key购买 nike

我正在尝试确定每次用户在 ChartJS 中选择新图表类型时重新加载 Canvas 的正确方法,现在它不会更改图表类型:

chartJs.js

 var ctx = document.getElementById("myChart").getContext("2d");
ctx.canvas.width = 600;
ctx.canvas.height = 200;
var determineChart = document.getElementById("chartType");
if( determineChart = "line") {
var myChart = new Chart(ctx).Line(data, options);
myChart.destroy();
}
else if (determineChart = "column"){
var myChart = new Chart(ctx).Bar(data, options);

}

index.html

<select id="chartType">
<option value="line">Line</option>
<option value="column">Column</option>
<option value="area">Area</option>
<option value="areaspline">Area Spline</option>
<option value="pie">Pie(Test)</option>
</select>

最佳答案

一个问题是在你的条件检查。此外,我不会将 if/else 逻辑与可用的图表类型相结合。

var ctx = document.getElementById("myChart").getContext("2d");
ctx.canvas.width = 600;
ctx.canvas.height = 200;

var dataMap = {
'line': {
method: 'Line',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 40]
}, {
label: "My Second dataset",
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,0.8)",
highlightFill: "rgba(151,187,205,0.75)",
highlightStroke: "rgba(151,187,205,1)",
data: [28, 48, 40, 19, 86, 27, 90]
}],
}
},
'pie': {
method: 'Pie',
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"
}]
}
};

var currentChart;

function updateChart() {
if(currentChart){currentChart.destroy();}

var determineChart = $("#chartType").val();

var params = dataMap[determineChart]
currentChart = new Chart(ctx)[params.method](params.data, {});
}

$('#chartType').on('change', updateChart)
updateChart();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.js'></script>
<canvas id="myChart"></canvas>
<select id="chartType">
<option value="line">Line</option>
<option value="pie">Pie</option>
</select>

关于javascript - ChartJS 根据下拉选择更改图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33260212/

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