我正在尝试使用画布生成一个简单的饼图,但是当将数据分配给用于绘制该图的数组时,它不显示任何内容。我似乎无法确切找出问题所在。
我曾经尝试使用循环将数组转换为整数,但是它仍然不会使用数据绘制图形。
function draw() {
var n = document.getElementById("data").value;
var values = n.split(",");
//document.write(values);
var colors = [ "blue", "red", "yellow", "green", "black" ];
var canvas = document.getElementById( "myCanvas");
var context = canvas.getContext( "2d" );
// grey background
context.fillStyle = "rgb(200,200,200)";
context.fillRect (0, 0, 600, 450);
//iterate through array and assign values to integers
for( var i = 0; i < values.length; i++ ){
values[i] = parseInt(values[i]);
}
// get length of data array
var dataLength = values.length;
// variable to store all values
var total = 0;
// calculate total
for( var i = 0; i < dataLength; i++ ){
// add data value to total
total += values[ i ];
}
// declare X and Y coordinates
var x = 100;
var y = 100;
var radius = 100;
// declare starting point
var startingPoint = 0;
for( var i = 0; i < dataLength; i++ ){
// calculate percent of total for current value
var percent = values[ i ][ 1 ] * 100 / total;
// calculate end point using the percentage (2 is the final point for the chart)
var endPoint = startingPoint + ( 2 / 100 * percent );
// draw chart segment for current element
context.beginPath();
// select corresponding color
context.fillStyle = colors[ i ];
context.moveTo( x, y );
context.arc( x, y, radius, startingPoint * Math.PI, endPoint * Math.PI );
context.fill();
// starting point for next element
startingPoint = endPoint;
}
}
<html>
<head>
<title> Easy Graph</title>
<link rel="stylesheet" href="stylesheet.css">
<style type = "text/css">
canvas {
border: 2px solid black;
}
</style>
<script type="text/javascript" src="pie.js">
</script>
</head>
<body>
<h2> Pie chart </h2>
<h2> Enter values seperated by commas</h2>
<input type="text" name="number" id="data"><br>
<input type="button" value="submit" name="submit" onclick = "draw();">
<input type="button" value="Clear" name="Clear" onclick="reset()"><br><br>
<canvas id ="myCanvas" width= "600" height= "300">
</canvas>
</body>
</html>
答案 0 :(得分:0)
这是错误的:
var percent = values[ i ][ 1 ] * 100 / total;
应该是这样
var percent = values[ i ] * 100 / total;
您正试图在数组中找到不存在的位置。