#javascript #chart.js
#JavaScript #chart.js
Вопрос:
У меня есть функция calc, которая выполняет некоторые вычисления, а затем передает результаты этих вычислений объекту в массиве surveyResults. После выполнения этих вычислений я затем вставляю и визуализирую HTML в DOM, который извлекает данные для отображения из массива surveyResult.
После этого у меня есть объект с именем chartResults, который создает диаграмму с chart.js . Я хочу обновить массив «данных», который находится внутри массива datasets, который находится внутри объекта chartResults. Я хочу обновить его, используя данные для yearOneSaving, yearTwoSaving и т. Д.
Как бы я это сделал? chartResults[2].data = Сохранение за год; а затем повторить 10 раз?
Отредактировано для добавления — HTML и CSS, чтобы вы могли видеть, как это работает. Введите любое число для каждого поля ожидайте, что «системный ежемесячный платеж» должен = 26,26 и «ежемесячный платеж за газ» = 35. Теперь вы можете увидеть диаграмму, генерируемую при нажатии кнопки рассчитать
const calculate = document.getElementById('one');
const resultsContainer = document.querySelector('.card-wrapper-results');
let surveyResults = [
{
savings: 10.23,
price: 35.84,
priceEnd: 20.2
}
];
calculate.addEventListener('click', calc);
function calc(event) {
event.preventDefault();
// Do the calculations.
let gas = parseFloat(document.getElementById('gas').value);
let boilerPrice = parseFloat(document.getElementById('price').value);
let gasSaving;
let smartSaving;
let resu<
let totalSaving;
smartSaving = gas * 0.2;
gasSaving = gas * 0.3;
totalSaving = smartSaving gasSaving;
result = boilerPrice - totalSaving;
surveyResults[0].savings = totalSaving;
surveyResults[0].price = boilerPrice;
surveyResults[0].priceEnd = resu<
//Calculations For Chart Data.
yearOneSaving = totalSaving * 12 * 0.03;
yearTwoSaving = totalSaving * 12 * 0.03 * 0.03;
yearThreeSaving = totalSaving * 12 * 0.03 * 0.03 * 0.03;
yearFourSaving = totalSaving * 12 * 0.03 * 0.03 * 0.03 * 0.03;
yearFiveSaving = totalSaving * 12 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03;
yearSixSaving = totalSaving * 12 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03;
yearSevenSaving = totalSaving * 12 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03;
yearEightSavings = totalSaving * 12 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03;
YearNineSaving = totalSaving * 12 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03;
YearTenSaving = totalSaving * 12 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03;
// Generate HTML to show the chart in.
let displayResults = surveyResults.map(
(item) => `
<div class="card2-results">
<h1>Scrappage Payment</h1>
<p class="job-title">Vaillant EcoTech Plus</p>
<h2 class="about-h2">£507.23</h2>
<ul class="about-payment">
<li><i class="fas fa-check"></i> AAA Rated Vaillant Ecotech Plus</li>
<li><i class="fas fa-check"></i> 10 Year Guaranty</li>
<li><i class="fas fa-check"></i> Big Gas Bill Savings</li>
<li><i class="fas fa-check"></i> Which Boiler Of The Year</li>
</ul>
<a href="" class="btn-results">30% Lower Gas Bill</a>
</div>
<div class="card2-results">
<h1>Smart Allowance</h1>
<p class="job-title">Hive Smart Heating</p>
<h2 class="about-h2">
£201.14
</h2>
<ul class="about-payment">
<li><i class="fas fa-check"></i> Gen 3 Smart Heating System</li>
<li><i class="fas fa-check"></i> 10 Year Guaranty</li>
<li><i class="fas fa-check"></i> Big Gas Bill Savings</li>
<li><i class="fas fa-check"></i> Phone App Controls</li>
</ul>
<a href="" class="btn-results">18% Lower Gas Bill</a>
</div>
<div class="card3-chart">
<h1>Yearly Gas Savings</h1>
<p class="job-title">Gen 3 Smart Heating</p>
<canvas id="myChart"></canvas>
</div>
<div class="card2-results">
<h1>Monthly Payment </h1>
<p class="job-title">EcoTech Plus</p>
<h2 class="about-h2">
£${item.price.toFixed(2)}
</h2>
<ul class="about-payment">
<li><i class="fas fa-check"></i> Supply amp; Installation RRP £3699.00</li>
<li><i class="fas fa-check"></i> Total Scrappage Payment £708.37</li>
<li><i class="fas fa-check"></i> Net Price £2991.63</li>
<li><i class="fas fa-check"></i> Hive Smart Heating System Included</li>
</ul>
<a href="" class="btn-results">£708.37 Saving</a>
</div>
<div class="card2-results">
<h1>Monthly Gas Savings</h1>
<p class="job-title">Instant Savings</p>
<h2 class="about-h2">£${item.savings.toFixed(2)}</h2>
<ul class="about-payment">
<li><i class="fas fa-check"></i> Start Saving Straightaway</li>
<li><i class="fas fa-check"></i> 30% Saving From EcoTech Plus</li>
<li><i class="fas fa-check"></i> 18% Saving From Hive Smart Heating</li>
<li><i class="fas fa-check"></i> Hive Smart Heating System Included</li>
</ul>
<a href="" class="btn-results">1st Year £336</a>
</div>
<div class="card3">
<h1>Net Installation Payment</h1>
<p class="job-title">Installation Price With Gas Savings</p>
<h2 class="about-h2">
£${item.priceEnd.toFixed(2)} pcm
</h2>
<div class="trust-logos">
<!-- trustpilot logo-->
<div class="trustpilot-container">
<img src="./img/trustpilot.png" class="trustpilot" alt="">
</div>
<!-- which logo-->
<div class="which-container">
<img src="./img/which.png" class="which" alt="">
</div>
<!--Gas Safe Logo-->
<div class="gas-container">
<img src="./img/Gas-Safe-Registered.png" class="gas" alt="">
</div>
<!-- FCA logo-->
<div class="fca-container">
<img src="./img/fca-logo-social-media.jpg" class="fca" alt="">
</div>
</div>
<a href="" class="btn-results-approved">Installation Approved</a>
</div>
`
);
// Canvas element exists after this line.
resultsContainer.innerHTML = displayResults;
// Now the myChart element is in the DOM, select it.
let myChart = document.getElementById('myChart').getContext('2d');
// Create a new chart.
let chartResults = new Chart(myChart, {
type: 'bar',
data: {
labels: [ 'Year 1', 'Year 2', 'Year 3', 'Year 4', 'Year 5', 'Year 6', 'Year 8', 'Year 9', 'Year 10' ],
datasets: [
{
label: 'Savings Per Year £',
data: [ 342, 410, 443, 501, 557, 602, 673, 702, 764, 823 ],
backgroundColor: '#168ecf'
}
]
},
options: {}
});
}
/* Survery Section Start */
.survery {
background-color: #1b262c;
padding-bottom: 100px;
}
.survery-h1 {
color: white;
text-align: center;
padding-top: 5rem;
}
input {
text-indent: 10px;
}
.survery-questions {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
.home-name-footer {
width: 600px;
height: 45px;
margin-bottom: 3em;
margin-left: 90px;
margin-right: 25px;
}
.home-phone-footer {
height: 45px;
margin-bottom: 3em;
width: 600px;
margin-left: 25px;
}
.home-email-footer {
width: 600px;
height: 45px;
margin-bottom: 3em;
margin-left: 90px;
margin-right: 25px;
}
#input {
background: #ffffff;
border: 1px solid #eaeaea;
}
.btn-calc {
padding: 1rem 2.5rem;
width: 15rem;
background-color: #168ecf;
text-transform: uppercase;
text-decoration: none;
font-family: 'Roboto', sans-serif;
font-size: 1rem;
font-weight: 900;
color: #eee;
transition: all .5s;
margin-bottom: 3rem;
margin-top: 1rem;
text-align: center;
border: none;
}
.thebutton {
margin-top: 50px;
text-align: center;
align-items: center;
width: 100%;
}
/* Calculation Results Start */
.section-results {
margin-top: 6rem;
}
.results-h1 {
text-align: center;
margin-top: 5rem;
}
.fa-plus-square {
font-size: 6rem;
color: #168ecf;
}
.uk-market-title {
margin-top: 100px;
}
.uk-market {
color: #24272b;
text-align: center;
}
.heading::after {
content: "";
width: 10rem;
height: 0.8rem;
background-color: #168ecf;
position: absolute;
bottom: -2rem;
left: 50%;
transform: translateX(-50%);
border-radius: 2rem;
}
.card-wrapper-results {
display: flex;
align-items: center;
align-content: center;
flex-direction: column;
}
.card2-results {
width: 35rem;
background-color: white;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
margin: 2rem 0;
box-shadow: .5rem .5rem 3rem rgba(0, 0, 0, 0.3);
}
.card3 {
width: 74rem;
background-color: white;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
margin: 2rem 0;
box-shadow: .5rem .5rem 3rem rgba(0, 0, 0, 0.3);
}
.card3-chart {
width: 74rem;
background-color: white;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
margin: 2rem 0;
box-shadow: .5rem .5rem 3rem rgba(0, 0, 0, 0.3);
padding-left: 60px;
padding: 60px;
padding-bottom: 90px;
}
.profile-image2 {
border-radius: 50%;
border: 3px solid white;
margin-top: -7rem;
z-index: 999;
}
.card2-results .card3 h1 {
font-size: 2.5rem;
color: #333;
margin: 1.5rem;
}
.job-title-results {
color: #777;
font-size: 1.5rem;
font-weight: 300;
margin-top: -1rem;
}
.about-results {
font-family: 'Roboto', sans-serif;
font-size: 1rem;
font-weight: 700;
line-height: 27px;
margin: 1.5rem;
list-style: none;
color: #333;
margin-top: -5px;
padding-right: 25px;
}
.about-h2 {
font-family: 'Roboto', sans-serif;
font-size: 4rem;
font-weight: 700;
line-height: 27px;
margin: 1.5rem;
list-style: none;
color: #333;
margin-top: 30px;
padding-right: 25px;
}
.about-payment {
font-family: 'Roboto', sans-serif;
font-size: 1rem;
font-weight: 700;
line-height: 27px;
margin: 1.5rem;
list-style: none;
color: #333;
margin-top: 2rem;
padding-right: 25px;
}
.fa-times {
color: #c41a0e;
}
.fa-check {
color: green;
}
.btn-results {
padding: 1rem 2.5rem;
width: 25rem;
background-color: #168ecf;
text-transform: uppercase;
text-decoration: none;
font-family: 'Roboto', sans-serif;
font-size: 2rem;
font-weight: 900;
color: #eee;
transition: all .5s;
margin-bottom: 3rem;
margin-top: 1rem;
text-align: center;
}
.btn-results-approved {
padding: 1rem 2.5rem;
width: rem;
background-color: #168ecf;
text-transform: uppercase;
text-decoration: none;
font-family: 'Roboto', sans-serif;
font-size: 2rem;
font-weight: 900;
color: #eee;
transition: all .5s;
margin-bottom: 3rem;
margin-top: 1rem;
}
.strike {
color: red;
padding-bottom: 10px;
}
.btn-red {
background-color: #c41a0e;
}
.btn-green {
background-color: green;
}
.card2 .btn:hover {
transform: translateY(-2px);
box-shadow: .5rem .5rem 2rem rgba(0, 0, 0, 0.3);
}
.card2 .btn:active {
transform: translateY(0);
box-shadow: none;
}
@media screen and (min-width: 700px) {
.card-wrapper-results {
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
align-items: center;
}
.card2-results {
margin: 2rem;
}
}
/* Calculation Results End */
<!-- Survery Start -->
<section class="survery">
<div class="survery-title">
<h1 class="survery-h1">Scrappage Payment Survey</h1>
</div>
<form action="">
<div class="survery-questions">
<div class="name-form">
<input type="text" placeholder="Gas Supplier" class="home-name-footer" id="input" required>
</div>
<div class="phone-form">
<input type="text" placeholder="Gas Meter Serial No." class="home-phone-footer" id="input" required>
</div>
<div class="email-form">
<input placeholder="Monthly Gas Spend" class="home-email-footer" id="gas" required>
</div>
<div class="phone-form">
<input type="text" placeholder="System Monthly Payment" class="home-phone-footer" id="price" required>
</div>
<div class="name-form">
<input type="text" placeholder="Number Of Bathrooms" class="home-name-footer" id="input" required>
</div>
<div class="phone-form">
<input type="text" placeholder="Number Of Radiators" class="home-phone-footer" id="input" required>
</div>
<div class="name-form">
<input type="text" placeholder="System Size Required (Kw)" class="home-name-footer" id="input" required>
</div>
<div class="phone-form">
<input type="text" placeholder="Number Of Residents" class="home-phone-footer" id="input" required>
</div>
<div class="thebutton">
<button class="btn-calc" id="one">Calculate</button>
</form>
</div>
</div>
</section>
<!-- Survery End-->
<!-- Survey Results Start-->
<section class="section-results">
<div class="container-results">
<h1 class="heading">Your Scrappage Payment Offer</h1>
<div class="card-wrapper-results">
<div class="card2-results">
<h1>Scrappage Payment </h1>
<p class="job-title">Vaillant EcoTech Plus</p>
<h2 class="about-h2">
£507.23
</h2>
<ul class="about-payment">
<li><i class="fas fa-check"></i> AAA Rated Vaillant Ecotech Plus</li>
<li><i class="fas fa-check"></i> 10 Year Guaranty</li>
<li><i class="fas fa-check"></i> Big Gas Bill Savings</li>
<li><i class="fas fa-check"></i> Which Boiler Of The Year</li>
</ul>
<a href="" class="btn-results">30% Lower Gas Bill</a>
</div>
<div class="card2-results">
<h1>Smart Allowance</h1>
<p class="job-title">Hive Smart Heating</p>
<h2 class="about-h2">
£201.14
</h2>
<ul class="about-payment">
<li><i class="fas fa-check"></i> Gen 3 Smart Heating System</li>
<li><i class="fas fa-check"></i> 10 Year Guaranty</li>
<li><i class="fas fa-check"></i> Big Gas Bill Savings</li>
<li><i class="fas fa-check"></i> Phone App Controls</li>
</ul>
<a href="" class="btn-results">18% Lower Gas Bill</a>
</div>
<div class="card3">
<h1>Yearly Gas Savings</h1>
<p class="job-title">Gen 3 Smart Heating</p>
<canvas id="myChart">
</canvas>
</div>
<div class="card2-results">
<h1>Monthly Payment </h1>
<p class="job-title">EcoTech Plus</p>
<h2 class="about-h2">
£35.82
</h2>
<ul class="about-payment">
<li><i class="fas fa-check"></i> Supply amp; Installation RRP £3699.00</li>
<li><i class="fas fa-check"></i> Total Scrappage Payment £708.37</li>
<li><i class="fas fa-check"></i> Net Price £2991.63</li>
<li><i class="fas fa-check"></i> Hive Smart Heating System Included</li>
</ul>
<a href="" class="btn-results">£708.37 Saving</a>
</div>
<div class="card2-results">
<h1>Monthly Gas Savings</h1>
<p class="job-title">Instant Savings</p>
<h2 class="about-h2">
£28.02
</h2>
<ul class="about-payment">
<li><i class="fas fa-check"></i> Start Saving Straightaway</li>
<li><i class="fas fa-check"></i> 30% Saving From EcoTech Plus </li>
<li><i class="fas fa-check"></i> 18% Saving From Hive Smart Heating</li>
<li><i class="fas fa-check"></i> Hive Smart Heating System Included</li>
</ul>
<a href="" class="btn-results">1st Year £336</a>
</div>
<div class="card3">
<h1>Net Installation Payment</h1>
<p class="job-title">Installation Price With Gas Savings</p>
<h2 class="about-h2">
£7.80 pcm
</h2>
<div class="trust-logos">
<!-- trustpilot logo-->
<div class="trustpilot-container">
<img src="./img/trustpilot.png" class="trustpilot" alt="">
</div>
<!-- which logo-->
<div class="which-container">
<img src="./img/which.png" class="which" alt="">
</div>
<!--Gas Safe Logo-->
<div class="gas-container">
<img src="./img/Gas-Safe-Registered.png" class="gas" alt="">
</div>
<!-- FCA logo-->
<div class="fca-container">
<img src="./img/fca-logo-social-media.jpg" class="fca" alt="">
</div>
</div>
<a href="" class="btn-results-approved">Installation Approved</a>
</div>
</div>
</div>
<!-- Survey Results End-->
<!-- JS Scripts Start -->
<script src="app.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"
integrity="sha512-s xg36jbIujB2S2VKfpGmlC3T5V2TF3lY48DX7u2r9XzGzgPsa6wTpOQA7J9iffvdeBN0q9tKzRxVxw1JviZPg=="
crossorigin="anonymous"></script>
<!-- JS Scripts ends -->
</body>
</html>
Комментарии:
1. Может быть, использовать цикл for с
Math.pow
for 0.03? 🙂2. Не забудьте добавить HTML-код в фрагмент, чтобы
document.getElementById('one');
он (и другие ссылки на элементы документа) работал.3. Я обновил, чтобы добавить html и css. Отзывчивость еще не выполнена, поэтому, пожалуйста, просматривайте в полном браузере
Ответ №1:
Вам нужно установить некоторые переменные и использовать их вместо данных жесткого кода….
Итак…..
// Canvas element exists after this line.
resultsContainer.innerHTML = displayResults;
// Now the myChart element is in the DOM, select it.
let myChart = document.getElementById('myChart').getContext('2d');
// Create a new chart.
let chartResults = new Chart(myChart, {
type: 'bar',
data: {
labels: [ 'Year 1', 'Year 2', 'Year 3', 'Year 4', 'Year 5', 'Year 6', 'Year 8', 'Year 9', 'Year 10' ],
datasets: [
{
label: 'Savings Per Year £',
data: [ 342, 410, 443, 501, 557, 602, 673, 702, 764, 823 ],
backgroundColor: '#168ecf'
}
]
},
options: {}
});
становится чем-то вроде…..
var savingsperyear = [ 342, 410, 443, 501, 557, 602, 673, 702, 764, 823 ];
// Canvas element exists after this line.
resultsContainer.innerHTML = displayResults;
// Now the myChart element is in the DOM, select it.
let myChart = document.getElementById('myChart').getContext('2d');
// Create a new chart.
let chartResults = new Chart(myChart, {
type: 'bar',
data: {
labels: [ 'Year 1', 'Year 2', 'Year 3', 'Year 4', 'Year 5', 'Year 6', 'Year 8', 'Year 9', 'Year 10' ],
datasets: [
{
label: 'Savings Per Year £',
data: savingsperyear,
backgroundColor: '#168ecf'
}
]
},
options: {}
});
(это сохраняет данные о загрузке страницы …)
Затем, чтобы обновить его, в вашей функции calc
yearOneSaving = totalSaving * 12 * 0.03;
yearTwoSaving = totalSaving * 12 * 0.03 * 0.03;
yearThreeSaving = totalSaving * 12 * 0.03 * 0.03 * 0.03;
yearFourSaving = totalSaving * 12 * 0.03 * 0.03 * 0.03 * 0.03;
yearFiveSaving = totalSaving * 12 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03;
yearSixSaving = totalSaving * 12 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03;
yearSevenSaving = totalSaving * 12 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03 * 0.03;
......
вам нужно снова установить массив…
// first, empty the array
savingsperyear.length = 0;
// then, fill it with what you need (note I got a bit lost with your code, but this should get you going.....! :)
savingsperyear.push(yearOneSaving);
savingsperyear.push(yearTwoSaving);
savingsperyear.push(yearThreeSaving);
// etc..... (there are other ways to do this, I'm just showing it step by step)
Комментарии:
1. Когда я пытаюсь это сделать, я получаю сообщение об ошибке savingsPerYear не определено в консоли
2. поместите var savingsperyear в начало функции (или вне функции) — в JS вам нужно объявить свои переменные перед их использованием.