我有一个网络应用程序,用户可以使用Chart.js绘制图表。
我在点击按钮时收集表单数据,正确格式化然后想要渲染图表。
以下是代码:
// /public/main.js
const chartData = {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 16, 2, 3],
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)'
]
}]
};
const barOptions = {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
};
const ctx = document.getElementById("myChart").getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar',
data: chartData,
options: barOptions
});
// Get Chart Info from form
$(document).ready(function() {
$("#render_btn").on("click", function(e) {
e.preventDefault();
// First grab form data off the page
const formData = $("form").serializeArray();
// Get Chart Type Seperate from Form Data
const chartType = document.getElementById('chart_type').value;
// Create a data Object for Chart constructor to use
const chartData = {
datasets: []
};
let datasetsItem = {};
// Convert formData array to chartData object
formData.forEach(function(value, index) {
if (formData[index].name == 'labels') {
chartData[(formData[index].name)] = formData[index].value;
} else {
datasetsItem[formData[index].name] = formData[index].value;
chartData.datasets[0] = datasetsItem;
}
});
// Now we have to do some converting i.e., chartData.labels must be
// converted to array from string etc
chartData.datasets[0].backgroundColor = splitString(chartData.datasets[0].backgroundColor);
chartData.datasets[0].data = strToNumberArray(chartData.datasets[0].data);
chartData.labels = splitString(chartData.labels);
// Check if succesful
try {
if (!(chartData.datasets[0].backgroundColor) || !(chartData.datasets[0].data) || !(chartData.labels)) {
throw new Error("Input Error. Recheck your form data.");
}
myChart.update({
type: chartType,
data: chartData
});
} catch (error) {
alert(error);
}
// ============================================================= //
// ============= Function definitions ========================== //
// ============================================================= //
function splitString(strToSplit, separator = ',') {
if (strToSplit === undefined) {
console.log("Error: splitString is empty.");
return "";
}
// Test for a comma in the string
const result = /,+/.test(strToSplit);
if (!result) {
alert(`Comma delimiter missing from ${strToSplit}`);
return false;
}
// Split a string into an array and trim any whitespace
let arrayOfStrings = strToSplit.split(separator);
arrayOfStrings.forEach(function(value, index) {
arrayOfStrings[index] = value.trim();
});
return arrayOfStrings;
}
// Function to convert string to an array then convert each element to a number
function strToNumberArray(str, separator = ',') {
if (str === undefined) {
alert('Error: string is empty.');
return "";
}
// Test for a comma in the string
const result = /,+/.test(str);
if (!result) {
alert(`Comma delimiter missing from ${str}`);
return false;
}
let arrayOfNumbers = str.split(separator).map(Number);
return arrayOfNumbers;
}
// ============================================================== //
// ================== End Function Definitions ================== //
// ============================================================== //
}); // .on "click"
});
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
<h2>Input your values:</h2>
<!-- Chart Input Form -->
<!-- We dont want chart_type as part of form when we use serializeArray
gather the data and use in chartData object -->
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="form-group">
<label for="chart_type">Chart Type</label>
<input type="text" name="type" class="form-control" id="chart_type" placeholder="Chart Type">
</div>
</div>
</div>
<form>
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="form-group">
<label for="chart_Label">Chart Label</label>
<input type="text" name="label" class="form-control" id="chart_Label" placeholder="Chart Label">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col-md-offset-4">
<div class="form-group">
<label for="chart_labels">Chart Labels</label>
<input type="text" name="labels" class="form-control" id="chart_labels" placeholder="Apr, May, June Note:Seperated by Commas">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col-md-offset-4">
<div class="form-group">
<label for="chart_data">Chart Data</label>
<input type="text" name="data" class="form-control" id="chart_data" placeholder="i.e., 25 44 60 etc">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col-md-offset-4">
<div class="form-group">
<label for="chart_colors">Chart Colors</label>
<input type="text" name="backgroundColor" class="form-control" id="chart_colors" placeholder="i.e., red, blue, yellow, purple">
</div>
</div>
</div>
<div class="row">
<div class="col-md-4 col-md-offset-5">
<button class="btn btn-primary btn-lg" id="render_btn">Render Graph</button>
</div>
</div>
</form>
当我点击按钮时,我什么都没得到。
如果我使用某些数据填充图表数据对象并全局声明新的myChart
,那么在页面加载时图表呈现正常但我添加的任何新数据然后单击表单按钮会暂时呈现然后消失(! ?)
理想情况下,我想要一个空白画布,让用户输入数据,然后单击渲染按钮并有图表。我看过网上但没有涉及我能找到的表单和事件处理程序。
我查看了Chart.js文档并尝试使用他们的示例无效/更新和渲染。
任何帮助都非常感谢...
更新:好的代码片段正在运行我遇到的问题。当您填写表单并单击渲染时,我什么也得不到。谢谢我从未使用过代码片段。任何人都可以使用它吗? 附: - 我将e.preventDefault添加到片段中,认为默认操作可能与Chart.js相关。不好。此外,所有值都应以逗号分隔。
答案 0 :(得分:1)
update
函数的文档为:
触发图表更新。 更新数据对象后可以安全地调用。这将更新所有比例,图例,然后重新渲染图表。
因此,您必须更新数据对象,而不是在update
方法中传递更新的数据对象。该方法仅接受以下属性:
在您的示例中,您必须更改以下代码:
myChart.update({
type: chartType,
data: chartData
});
到
myChart.type = chartType;
myChart.data = chartData;
myChart.update();
以下是带有更改的代码段:
// /public/main.js
const chartData = {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 16, 2, 3],
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)'
]
}]
};
const barOptions = {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
};
const ctx = document.getElementById("myChart").getContext('2d');
const myChart = new Chart(ctx, {
type: 'bar',
data: chartData,
options: barOptions
});
// Get Chart Info from form
$(document).ready(function() {
$("#render_btn").on("click", function(e) {
e.preventDefault();
// First grab form data off the page
const formData = $("form").serializeArray();
// Get Chart Type Seperate from Form Data
const chartType = document.getElementById('chart_type').value;
// Create a data Object for Chart constructor to use
const chartData = {
datasets: []
};
let datasetsItem = {};
// Convert formData array to chartData object
formData.forEach(function(value, index) {
if (formData[index].name == 'labels') {
chartData[(formData[index].name)] = formData[index].value;
} else {
datasetsItem[formData[index].name] = formData[index].value;
chartData.datasets[0] = datasetsItem;
}
});
// Now we have to do some converting i.e., chartData.labels must be
// converted to array from string etc
chartData.datasets[0].backgroundColor = splitString(chartData.datasets[0].backgroundColor);
chartData.datasets[0].data = strToNumberArray(chartData.datasets[0].data);
chartData.labels = splitString(chartData.labels);
// Check if succesful
try {
if (!(chartData.datasets[0].backgroundColor) || !(chartData.datasets[0].data) || !(chartData.labels)) {
throw new Error("Input Error. Recheck your form data.");
}
myChart.type = chartType;
myChart.data = chartData;
myChart.update();
} catch (error) {
alert(error);
}
// ============================================================= //
// ============= Function definitions ========================== //
// ============================================================= //
function splitString(strToSplit, separator = ',') {
if (strToSplit === undefined) {
console.log("Error: splitString is empty.");
return "";
}
// Test for a comma in the string
const result = /,+/.test(strToSplit);
if (!result) {
alert(`Comma delimiter missing from ${strToSplit}`);
return false;
}
// Split a string into an array and trim any whitespace
let arrayOfStrings = strToSplit.split(separator);
arrayOfStrings.forEach(function(value, index) {
arrayOfStrings[index] = value.trim();
});
return arrayOfStrings;
}
// Function to convert string to an array then convert each element to a number
function strToNumberArray(str, separator = ',') {
if (str === undefined) {
alert('Error: string is empty.');
return "";
}
// Test for a comma in the string
const result = /,+/.test(str);
if (!result) {
alert(`Comma delimiter missing from ${str}`);
return false;
}
let arrayOfNumbers = str.split(separator).map(Number);
return arrayOfNumbers;
}
// ============================================================== //
// ================== End Function Definitions ================== //
// ============================================================== //
}); // .on "click"
});
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
<h2>Input your values:</h2>
<!-- Chart Input Form -->
<!-- We dont want chart_type as part of form when we use serializeArray
gather the data and use in chartData object -->
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="form-group">
<label for="chart_type">Chart Type</label>
<input type="text" name="type" class="form-control" id="chart_type" placeholder="Chart Type">
</div>
</div>
</div>
<form>
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="form-group">
<label for="chart_Label">Chart Label</label>
<input type="text" name="label" class="form-control" id="chart_Label" placeholder="Chart Label">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col-md-offset-4">
<div class="form-group">
<label for="chart_labels">Chart Labels</label>
<input type="text" name="labels" class="form-control" id="chart_labels" placeholder="Apr, May, June Note:Seperated by Commas">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col-md-offset-4">
<div class="form-group">
<label for="chart_data">Chart Data</label>
<input type="text" name="data" class="form-control" id="chart_data" placeholder="i.e., 25 44 60 etc">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col-md-offset-4">
<div class="form-group">
<label for="chart_colors">Chart Colors</label>
<input type="text" name="backgroundColor" class="form-control" id="chart_colors" placeholder="i.e., red, blue, yellow, purple">
</div>
</div>
</div>
<div class="row">
<div class="col-md-4 col-md-offset-5">
<button class="btn btn-primary btn-lg" id="render_btn">Render Graph</button>
</div>
</div>
</form>