Draw a column chart
1.design the data, the structure should be like shown in this picture, and put them in a separate file.
2.draw a column chart to display the data (you don’t need to put the text for now)
一、效果预览
二、Column.html
代码如下(示例):
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CH1Ex4:Draw a column chart</title>
</head>
<body>
<input id="input" type="file"><br>
<canvas id="canvasOne" width="1080" height="480">
Your browser does not support HTML 5 Canvas.
</canvas>
</body>
<script type="text/javascript">
// 初始化canvas
var MyCanvas = document.getElementById("canvasOne");
var ctx = MyCanvas.getContext("2d");
ctx.fillStyle="#EEC900";
ctx.fillRect(0,0,1080,480);
var recWidth = 40; // 默认矩形宽度
var recColor1 = "#7AC5CD"; // 默认矩形颜色
var recColor2 = "#EE7942";
var recColor3 = "#8FBC8F";
var a = 10; // 默认数据转换倍率
var x = 20; // 初始绘制x坐标
var y = 400; // 初始绘制y坐标
var rul = 5; // 绘制标尺间隔长度
ctx.fillStyle="#F5F5F5";
ctx.font="15px Arial";
for(var i = 0; i < 7;i++){
ctx.fillText(0+i*rul,x,y-i*rul*a);
ctx.fillRect(x+20,y-i*rul*a,1080,2);
}
function drawRec(ctx,name,num1,num2,num3){
// 参数name的文本绘制
ctx.fillStyle="#fff";
ctx.font="30px Arial";
ctx.fillText(name,x+recWidth*2+40,y+30);
// 参数1、2、3的矩形绘制
ctx.fillStyle=recColor1;
ctx.fillRect(x=x+recWidth+20,y,recWidth,-num1*a);
ctx.fillStyle=recColor2;
ctx.fillRect(x=x+recWidth+20,y,recWidth,-num2*a);
ctx.fillStyle=recColor3;
ctx.fillRect(x=x+recWidth+20,y,recWidth,-num3*a);
x+=recWidth*2;
}
// 本地文件读取数据
const input = document.querySelector('input[type=file]')
input.addEventListener('change', ()=>{
const reader = new FileReader()
reader.readAsText(input.files[0],'utf8')
reader.onload = ()=>{
// 分行读取文件数据到lines数组
var lines = reader.result.split('\n');
// 遍历所有行数
var i = 1;
while(lines[i]!=null){
// 将每行的数据分别存到nums
var nums = lines[i].split(' ');
// 绘制条形图
drawRec(ctx,nums[0],nums[1],nums[2],nums[3]);
i++;
}
}
}, false)
</script>
</html>