如何将动态数字添加到chart.js图表 中?

问题描述 投票:0回答:2

我想制作一张在冠状病毒方面经过正面测试的人数和与冠状病毒有关的死亡人数的甜甜圈图,如何与图表顶部的容器中的数字相同?因此,需要将已确认的病例和死亡情况放入甜甜圈图。

非常感谢。很抱歉问了这么多问题,但是我从您的回答中学到了很多,而且我正在慢慢进步,但是我仍然是所有这些的初学者。

let tId;
window.addEventListener("load", function() {
  document.getElementById("countrySel").addEventListener("change", getCovidStats);
  document.getElementById("countrySel").value = "169";
  getCovidStats()
})

// Zorgt voor de optel annimatie
function countUp() {
  cnt += 100;
  let done = 0;
  let iMax = +document.getElementById('inwoners').getAttribute("max");
  if (cnt < iMax) document.getElementById('inwoners').innerText = cnt.toLocaleString('en');
  else done++
    let pMax = +document.getElementById('patienten').getAttribute("max");
  if (cnt < pMax) document.getElementById('patienten').innerText = cnt.toLocaleString('en');
  else done++
    let dMax = +document.getElementById('doden').getAttribute("max");
  if (cnt < dMax) document.getElementById('doden').innerText = cnt.toLocaleString('en');
  else done++



    document.getElementById('procent').innerHTML = ((Number(document.getElementById('doden').innerText.replace(/\D/g, "")) / Number(document.getElementById('patienten').innerText.replace(/\D/g, ""))) * 100).toLocaleString("en", {
      minimumFractionDigits: 2, // Minimum aantal getallen achter comma
      maximumFractionDigits: 2 // Maximum aantal getallen achter comma
    }) + "%"; // Zet een procent teken achter het getal
  if (done === 3) clearInterval(tId); 
}


function getCovidStats() {
  const cc = document.getElementById("countrySel").value; // Gekozen nummer van het land
  if (cc === "") return; // Als er een land gekozen is voer dan uit

  fetch('https://coronavirus-tracker-api.herokuapp.com/v2/locations/' + cc) // De database met gegevens van landen, CC is de country value die in de selector als waarde staat.
    .then(function(resp) {
      return resp.json()
    })
    .then(function(data) {
      let population = data.location.country_population; // Inwoners van het land gekozen in de selector
      let update = data.location.last_updated; // Laatste update van de data
      let confirmedCases = data.location.latest.confirmed; // Aantal geregistreerde geinfecteerden in het gekozen land
      let deaths = data.location.latest.deaths; // Aantal doden in het gekozen land

      document.getElementById('inwoners').innerText = population.toLocaleString('en'); // Inwoneraantal van het land
      document.getElementById('update').innerText = update.substr(0, 10);
      document.getElementById('patienten').innerText = // Aantal geregistreerde geinfecteerden
      document.getElementById('patienten').setAttribute("max", confirmedCases) 
      document.getElementById('doden').innerText = 0; // Aantal doden
      document.getElementById('doden').setAttribute("max", deaths)  
      document.getElementById('procent').innerText = 0 + "%" // Percentage overleden mensen van het aantal besmette mensen
      cnt = 0;
      tId = setInterval(countUp, 0.0001); // Snelheid van de counter

      document.getElementById('preciezeAantal').innerText= confirmedCases;  // Dit laat het niet afgeronde aantal besmettingen voor het geselecteerde land zien
      tId = setInterval(countUp, 1500); 
    })
    .catch(function() {
      console.log("error");
    })
  setInterval(getCovidStats, 43200000) // Zorgt ervoor dat de data om de 12 uur wordt geupdated
}
* {
	margin: 0;
	padding: 0;
}

html {
	height: 100%;
	width: 100%;
}
h1, h2 {
	font-family: 'Roboto', sans-serif;
	font-weight: 300;
	text-align: center;
	padding-bottom: 20px;
	font-size: 250%;
}

.subtitle, .over {
	padding: 20px;
	font-size: 150%;
}

body {
	background-color: #FFDC56;
	}

div {
	padding: 20px;
}

/* Add a black background color to the top navigation */
.topnav {
	background-color: #005A9C;
	overflow: hidden;
	font-family: 'Roboto', sans-serif;
	font-size: 75%;
	}

	.logo {
		float: left;
	}

	/* Style the links inside the navigation bar */
	.topnav a {
	float: right;
	color: #f2f2f2;
	text-align: center;
	padding: 14px 16px;
	text-decoration: none;
	font-size: 17px;
	}
	
	/* Change the color of links on hover */
	.topnav a:hover {
	background-color: #FFDC56;
	color: black;
	}
	
	/* Add a color to the active/current link */
	.topnav a.active {
	background-color: #4CAF50;
	color: white;
	}

.stats-container {
	text-align: center;
	float: right;
	display: inline-block;
}
.location-container {
	display: inline-block;
}
.data-container {
	border: 2px solid #005A9C;
	margin-right: 30%;
	margin-left: 30%;
}

h4, {
	font-size: 85%;
 	color: gray;
 	font-family: 'Roboto', sans-serif;
 	font-weight: 300;
 	text-align: center;
 	padding-top: 20px;
 	padding-left: 20px;
 	padding-right: 20px;
 	padding-bottom: 5px;
}

.over {
	font-family: 'Roboto', sans-serif;
	font-size: 100%;
	text-align: center;
}

.footer {
	font-family: 'Roboto', sans-serif;
	bottom: 0;
	font-size: 75%;
	padding: 5px;
}


.maatregelen {
	width: 35%;
	display: block;
	margin-left: auto;
	margin-right: auto;
	text-align: center;

}

.maatregelen-caption {
	text-align: center;
	font-family: 'Roboto', sans-serif;
	font-size: 80%;
}
<!DOCTYPE html>
<html>
<head>
	<title>Coronavirus Statistieken</title>  
	<meta charset="UTF-8">
	<link rel="shortcut icon" href="masker-emoji.png">
	<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400&display=swap" rel="stylesheet">
	<link rel="stylesheet" type="text/css" href="styles.css">
	<script src="app.js"></script>
	<script src="chart.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>

</head>
<body>
	<div class="topnav">
		<h1 class= "logo">Coronavirus</h1> 
		<a href="over.html">Over</a>
		<a class="active" href="index.html">STATS</a>
	  </div>

	<h2 class="subtitle">TITLE</h2>
	<div class="data-container">
		<div class="stats-container">
			<h4>TESTED POSITIVE</h4>
			<h1 id="patienten"></h1>
			<h4>DEATHS</h4>
			<h1 id="doden"></h1>
			<h4>Percentage deaths of patients</h4>
			<h1 id="procent"></h1>
		</div>
		<div class="location-container">
			<h4>Land</h4>
			<h1 id="country"><label for="countrySel">Country:</label>
				<select id="countrySel">
				  <option value="169">🇳🇱 </option>
				  <option value="120">🇩🇪 </option>
				  <option value="116">🇫🇷 </option>
				  <option value="201">🇪🇸 </option>
				  <option value="137">🇮🇹 </option>
				  <option value="187">🇷🇺 </option>
				  <option value="143">🇰🇷 </option>
				  <option value="225">🇺🇸 </option>
				</select>
			  </h1>
			<h4>Population</h4>
			<h1 id="inwoners"></h1>
			<h4>Last update</h4>
			<h1 id="update"></h1>
		</div>		
	</div>
	<h1>test:</h1><h1 id="preciezeAantal"></h1>
	<canvas id="doughnut-chart"></canvas>
	<script>
		// Bar chart 
new Chart(document.getElementById("doughnut-chart"), {
  type: 'doughnut',
  data: {
    labels: ["Deaths","Tested positive to Coronavirus"],
    datasets: [
      {
        label: ".",
        backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850","#3e95cd", "#8e5ea2","#3cba9f"],
        data: [100,200]
      }
    ]
  },
  options: {
    legend: { display: false },
    title: {
      display: true,
      text: 'Aantal besmettingen per land'
    }
  }
});
	</script>
	<h1 class="footer">Footer</a></h1>
</body>
</html>
javascript html json animation chart.js
2个回答
0
投票
您必须通过更改选择来获得“ max”属性,请参见HTML脚本标签:

let tId; window.addEventListener("load", function() { document.getElementById("countrySel").addEventListener("change", getCovidStats); document.getElementById("countrySel").value = "169"; getCovidStats() }) // Zorgt voor de optel annimatie function countUp() { cnt += 100; let done = 0; let iMax = +document.getElementById('inwoners').getAttribute("max"); if (cnt < iMax) document.getElementById('inwoners').innerText = cnt.toLocaleString('en'); else done++ let pMax = +document.getElementById('patienten').getAttribute("max"); if (cnt < pMax) document.getElementById('patienten').innerText = cnt.toLocaleString('en'); else done++ let dMax = +document.getElementById('doden').getAttribute("max"); if (cnt < dMax) document.getElementById('doden').innerText = cnt.toLocaleString('en'); else done++ document.getElementById('procent').innerHTML = ((Number(document.getElementById('doden').innerText.replace(/\D/g, "")) / Number(document.getElementById('patienten').innerText.replace(/\D/g, ""))) * 100).toLocaleString("en", { minimumFractionDigits: 2, // Minimum aantal getallen achter comma maximumFractionDigits: 2 // Maximum aantal getallen achter comma }) + "%"; // Zet een procent teken achter het getal if (done === 3) clearInterval(tId); } function getCovidStats() { const cc = document.getElementById("countrySel").value; // Gekozen nummer van het land if (cc === "") return; // Als er een land gekozen is voer dan uit fetch('https://coronavirus-tracker-api.herokuapp.com/v2/locations/' + cc) // De database met gegevens van landen, CC is de country value die in de selector als waarde staat. .then(function(resp) { return resp.json() }) .then(function(data) { let population = data.location.country_population; // Inwoners van het land gekozen in de selector let update = data.location.last_updated; // Laatste update van de data let confirmedCases = data.location.latest.confirmed; // Aantal geregistreerde geinfecteerden in het gekozen land let deaths = data.location.latest.deaths; // Aantal doden in het gekozen land console.log(deaths) document.getElementById('inwoners').innerText = population.toLocaleString('en'); // Inwoneraantal van het land document.getElementById('update').innerText = update.substr(0, 10); document.getElementById('patienten').innerText = // Aantal geregistreerde geinfecteerden document.getElementById('patienten').setAttribute("max", confirmedCases) document.getElementById('doden').innerText = 0; // Aantal doden document.getElementById('doden').setAttribute("max", deaths) document.getElementById('procent').innerText = 0 + "%" // Percentage overleden mensen van het aantal besmette mensen cnt = 0; tId = setInterval(countUp, 0.0001); // Snelheid van de counter document.getElementById('preciezeAantal').innerText= confirmedCases; // Dit laat het niet afgeronde aantal besmettingen voor het geselecteerde land zien tId = setInterval(countUp, 1500); }) .catch(function() { console.log("error"); }) setInterval(getCovidStats, 43200000) // Zorgt ervoor dat de data om de 12 uur wordt geupdated }
* {
    margin: 0;
    padding: 0;
}

html {
    height: 100%;
    width: 100%;
}
h1,
h2 {
    font-family: "Roboto", sans-serif;
    font-weight: 300;
    text-align: center;
    padding-bottom: 20px;
    font-size: 250%;
}

.subtitle,
.over {
    padding: 20px;
    font-size: 150%;
}

body {
    background-color: #ffdc56;
}

div {
    padding: 20px;
}

/* Add a black background color to the top navigation */
.topnav {
    background-color: #005a9c;
    overflow: hidden;
    font-family: "Roboto", sans-serif;
    font-size: 75%;
}

.logo {
    float: left;
}

/* Style the links inside the navigation bar */
.topnav a {
    float: right;
    color: #f2f2f2;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    font-size: 17px;
}

/* Change the color of links on hover */
.topnav a:hover {
    background-color: #ffdc56;
    color: black;
}

/* Add a color to the active/current link */
.topnav a.active {
    background-color: #4caf50;
    color: white;
}

.stats-container {
    text-align: center;
    float: right;
    display: inline-block;
}
.location-container {
    display: inline-block;
}
.data-container {
    border: 2px solid #005a9c;
    margin-right: 30%;
    margin-left: 30%;
}

h4 {
    font-size: 85%;
    color: gray;
    font-family: "Roboto", sans-serif;
    font-weight: 300;
    text-align: center;
    padding-top: 20px;
    padding-left: 20px;
    padding-right: 20px;
    padding-bottom: 5px;
}

.over {
    font-family: "Roboto", sans-serif;
    font-size: 100%;
    text-align: center;
}

.footer {
    font-family: "Roboto", sans-serif;
    bottom: 0;
    font-size: 75%;
    padding: 5px;
}

.maatregelen {
    width: 35%;
    display: block;
    margin-left: auto;
    margin-right: auto;
    text-align: center;
}

.maatregelen-caption {
    text-align: center;
    font-family: "Roboto", sans-serif;
    font-size: 80%;
}
<!DOCTYPE html>
<html>

<head>
    <title>Coronavirus Statistieken</title>
    <meta charset="UTF-8">
    <link rel="shortcut icon" href="masker-emoji.png">
    <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400&display=swap" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="main.css">
    <script src="app.js"></script>
    <script src="script.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>

</head>

<body>
    <div class="topnav">
        <h1 class="logo">Coronavirus</h1>
        <a href="over.html">Over</a>
        <a class="active" href="index.html">STATS</a>
    </div>

    <h2 class="subtitle">TITLE</h2>
    <div class="data-container">
        <div class="stats-container">
            <h4>TESTED POSITIVE</h4>
            <h1 id="patienten"></h1>
            <h4>DEATHS</h4>
            <h1 id="doden"></h1>
            <h4>Percentage deaths of patients</h4>
            <h1 id="procent"></h1>
        </div>
        <div class="location-container">
            <h4>Land</h4>
            <h1 id="country"><label for="countrySel">Country:</label>
                <select id="countrySel">
                    <option value="169">🇳🇱 </option>
                    <option value="120">🇩🇪 </option>
                    <option value="116">🇫🇷 </option>
                    <option value="201">🇪🇸 </option>
                    <option value="137">🇮🇹 </option>
                    <option value="187">🇷🇺 </option>
                    <option value="143">🇰🇷 </option>
                    <option value="225">🇺🇸 </option>
                </select>
            </h1>
            <h4>Population</h4>
            <h1 id="inwoners"></h1>
            <h4>Last update</h4>
            <h1 id="update"></h1>
        </div>
    </div>
    <h1>test:</h1>
    <h1 id="preciezeAantal"></h1>
    <canvas id="doughnut-chart"></canvas>
    <script>
        let countrySel = document.getElementById('countrySel');
        countrySel.addEventListener("change", function () {
            deaths = document.getElementById("doden").getAttribute("max");
            positive_test = document.getElementById("patienten").getAttribute("max");

            new Chart(document.getElementById("doughnut-chart"), {
                type: 'doughnut',
                data: {
                    labels: ["Deaths", "Tested positive to Coronavirus"],
                    datasets: [
                        {
                            label: ".",
                            backgroundColor: ["#3e95cd", "#8e5ea2", "#3cba9f", "#e8c3b9", "#c45850", "#3e95cd", "#8e5ea2", "#3cba9f"],
                            data: [deaths, positive_test]
                        }
                    ]
                },
                options: {
                    legend: { display: false },
                    title: {
                        display: true,
                        text: 'Aantal besmettingen per land'
                    }
                }
            });
        });
    </script>
    <h1 class="footer">Footer</a></h1>
</body>

</html>

0
投票
将图表逻辑包装在函数中,以便可以将deathsconfirmedCases作为参数传递给它。然后,在deathsconfirmedCases具有它们的值之后调用该函数。

let tId; window.addEventListener("load", function() { document.getElementById("countrySel").addEventListener("change", getCovidStats); document.getElementById("countrySel").value = "169"; getCovidStats() }) // Zorgt voor de optel annimatie function countUp() { cnt += 100; let done = 0; let iMax = +document.getElementById('inwoners').getAttribute("max"); if (cnt < iMax) document.getElementById('inwoners').innerText = cnt.toLocaleString('en'); else done++ let pMax = +document.getElementById('patienten').getAttribute("max"); if (cnt < pMax) document.getElementById('patienten').innerText = cnt.toLocaleString('en'); else done++ let dMax = +document.getElementById('doden').getAttribute("max"); if (cnt < dMax) document.getElementById('doden').innerText = cnt.toLocaleString('en'); else done++ document.getElementById('procent').innerHTML = ((Number(document.getElementById('doden').innerText.replace(/\D/g, "")) / Number(document.getElementById('patienten').innerText.replace(/\D/g, ""))) * 100).toLocaleString("en", { minimumFractionDigits: 2, // Minimum aantal getallen achter comma maximumFractionDigits: 2 // Maximum aantal getallen achter comma }) + "%"; // Zet een procent teken achter het getal if (done === 3) clearInterval(tId); } function getCovidStats() { const cc = document.getElementById("countrySel").value; // Gekozen nummer van het land if (cc === "") return; // Als er een land gekozen is voer dan uit fetch('https://coronavirus-tracker-api.herokuapp.com/v2/locations/' + cc) // De database met gegevens van landen, CC is de country value die in de selector als waarde staat. .then(function(resp) { return resp.json() }) .then(function(data) { let population = data.location.country_population; // Inwoners van het land gekozen in de selector let update = data.location.last_updated; // Laatste update van de data let confirmedCases = data.location.latest.confirmed; // Aantal geregistreerde geinfecteerden in het gekozen land let deaths = data.location.latest.deaths; // Aantal doden in het gekozen land showChart(deaths,confirmedCases); document.getElementById('inwoners').innerText = population.toLocaleString('en'); // Inwoneraantal van het land document.getElementById('update').innerText = update.substr(0, 10); document.getElementById('patienten').innerText = // Aantal geregistreerde geinfecteerden document.getElementById('patienten').setAttribute("max", confirmedCases) document.getElementById('doden').innerText = 0; // Aantal doden document.getElementById('doden').setAttribute("max", deaths) document.getElementById('procent').innerText = 0 + "%" // Percentage overleden mensen van het aantal besmette mensen cnt = 0; tId = setInterval(countUp, 0.0001); // Snelheid van de counter document.getElementById('preciezeAantal').innerText= confirmedCases; // Dit laat het niet afgeronde aantal besmettingen voor het geselecteerde land zien tId = setInterval(countUp, 1500); }) .catch(function() { console.log("error"); }) setInterval(getCovidStats, 43200000) // Zorgt ervoor dat de data om de 12 uur wordt geupdated } function showChart(deaths,confirmedCases){ // Bar chart new Chart(document.getElementById("doughnut-chart"), { type: 'doughnut', data: { labels: ["Deaths","Tested positive to Coronavirus"], datasets: [ { label: ".", backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850","#3e95cd", "#8e5ea2","#3cba9f"], data: [deaths,confirmedCases] } ] }, options: { legend: { display: false }, title: { display: true, text: 'Aantal besmettingen per land' } } }); }
* {
	margin: 0;
	padding: 0;
}

html {
	height: 100%;
	width: 100%;
}
h1, h2 {
	font-family: 'Roboto', sans-serif;
	font-weight: 300;
	text-align: center;
	padding-bottom: 20px;
	font-size: 250%;
}

.subtitle, .over {
	padding: 20px;
	font-size: 150%;
}

body {
	background-color: #FFDC56;
	}

div {
	padding: 20px;
}

/* Add a black background color to the top navigation */
.topnav {
	background-color: #005A9C;
	overflow: hidden;
	font-family: 'Roboto', sans-serif;
	font-size: 75%;
	}

	.logo {
		float: left;
	}

	/* Style the links inside the navigation bar */
	.topnav a {
	float: right;
	color: #f2f2f2;
	text-align: center;
	padding: 14px 16px;
	text-decoration: none;
	font-size: 17px;
	}
	
	/* Change the color of links on hover */
	.topnav a:hover {
	background-color: #FFDC56;
	color: black;
	}
	
	/* Add a color to the active/current link */
	.topnav a.active {
	background-color: #4CAF50;
	color: white;
	}

.stats-container {
	text-align: center;
	float: right;
	display: inline-block;
}
.location-container {
	display: inline-block;
}
.data-container {
	border: 2px solid #005A9C;
	margin-right: 30%;
	margin-left: 30%;
}

h4, {
	font-size: 85%;
 	color: gray;
 	font-family: 'Roboto', sans-serif;
 	font-weight: 300;
 	text-align: center;
 	padding-top: 20px;
 	padding-left: 20px;
 	padding-right: 20px;
 	padding-bottom: 5px;
}

.over {
	font-family: 'Roboto', sans-serif;
	font-size: 100%;
	text-align: center;
}

.footer {
	font-family: 'Roboto', sans-serif;
	bottom: 0;
	font-size: 75%;
	padding: 5px;
}


.maatregelen {
	width: 35%;
	display: block;
	margin-left: auto;
	margin-right: auto;
	text-align: center;

}

.maatregelen-caption {
	text-align: center;
	font-family: 'Roboto', sans-serif;
	font-size: 80%;
}
<!DOCTYPE html>
<html>
<head>
	<title>Coronavirus Statistieken</title>  
	<meta charset="UTF-8">
	<link rel="shortcut icon" href="masker-emoji.png">
	<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400&display=swap" rel="stylesheet">
	<link rel="stylesheet" type="text/css" href="styles.css">
	<script src="app.js"></script>
	<script src="chart.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>

</head>
<body>
	<div class="topnav">
		<h1 class= "logo">Coronavirus</h1> 
		<a href="over.html">Over</a>
		<a class="active" href="index.html">STATS</a>
	  </div>

	<h2 class="subtitle">TITLE</h2>
	<div class="data-container">
		<div class="stats-container">
			<h4>TESTED POSITIVE</h4>
			<h1 id="patienten"></h1>
			<h4>DEATHS</h4>
			<h1 id="doden"></h1>
			<h4>Percentage deaths of patients</h4>
			<h1 id="procent"></h1>
		</div>
		<div class="location-container">
			<h4>Land</h4>
			<h1 id="country"><label for="countrySel">Country:</label>
				<select id="countrySel">
				  <option value="169">🇳🇱 </option>
				  <option value="120">🇩🇪 </option>
				  <option value="116">🇫🇷 </option>
				  <option value="201">🇪🇸 </option>
				  <option value="137">🇮🇹 </option>
				  <option value="187">🇷🇺 </option>
				  <option value="143">🇰🇷 </option>
				  <option value="225">🇺🇸 </option>
				</select>
			  </h1>
			<h4>Population</h4>
			<h1 id="inwoners"></h1>
			<h4>Last update</h4>
			<h1 id="update"></h1>
		</div>		
	</div>
	<h1>test:</h1><h1 id="preciezeAantal"></h1>
	<canvas id="doughnut-chart"></canvas>
	<script>
	
	</script>
	<h1 class="footer">Footer</a></h1>
© www.soinside.com 2019 - 2024. All rights reserved.