Chartjs-How to get rid of old data and of old graph in Chart.js?

1👍

You should not recreate chart since that is not allowed in v2, instead you need to replace the data:

<!DOCTYPE html>
<html>
<head>
	<title>hp mp</title>
	<meta charset="utf-8">
	<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.3/Chart.min.js"></script>
</head>

<body onload="hpmpGraph()">
	<script>
  	var myPieChart = null
        var config = {options:{},type:'pie'}
		function hpmpGraph() {
			var hp = document.hpmpForm.HP.value,
				mp = document.hpmpForm.MP.value,
				ctx = document.getElementById('hpmpratio').getContext('2d');
			
                        config.data = {
				labels: ["HP","MP"],
				datasets: 
					[{
						data: [hp,mp],
						backgroundColor: ["#EF0000","#0000EF"],
						hoverBackgroundColor: ["#FF0000","#0000FF"]
					}]
			};
			if(myPieChart == null){
                            myPieChart = new Chart(ctx, config);
                        }else{
                            myPieChart.update()
                        }
       
      
		}
	</script>

	<h1>HP & MP</h1>
	<form name=hpmpForm method=post>
		HP : <input type="text" name="HP" value="100"><br>
		MP : <input type="text" name="MP" value="100"><br>
		<button type="button" onClick="hpmpGraph();">Click</button>
		<h2>Pie graph</h2>
		<canvas id="hpmpratio" height="50"></canvas>
	</form>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
	<title>hp mp</title>
	<meta charset="utf-8">
	<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.3/Chart.min.js"></script>
</head>

<body onload="hpmpGraph()">
	<script>
		function hpmpGraph() {
			var hp = document.hpmpForm.HP.value,
				mp = document.hpmpForm.MP.value,
				ctx = document.getElementById('hpmpratio').getContext('2d');
				
			var	data = {
				labels: ["HP","MP"],
				datasets: 
					[{
						data: [hp,mp],
						backgroundColor: ["#EF0000","#0000EF"],
						hoverBackgroundColor: ["#FF0000","#0000FF"]
					}]
			};
			var options = {};

			var myPieChart = new Chart(ctx, {
				type: 'pie',
				data: data,
				options: options
			});
		}
	</script>

	<h1>HP & MP</h1>
	<form name=hpmpForm method=post>
		HP : <input type="text" name="HP" value="100"><br>
		MP : <input type="text" name="MP" value="100"><br>
		<button type="button" onClick="hpmpGraph();">Click</button>
		<h2>Pie graph</h2>
		<canvas id="hpmpratio" height="50"></canvas>
	</form>
</body>
</html>

Leave a comment