柱状图
Posted 3542446186qq
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了柱状图相关的知识,希望对你有一定的参考价值。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>柱状图</title>
<style type="text/css">
canvas {
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas width="800px" height="500px"></canvas>
<script type="text/javascript">
var myCanvas = document.querySelector("canvas");
var ctx = myCanvas.getContext("2d");
var space= 100;
//动态获取画布大小
var canvasW = ctx.canvas.width;
var canvasH = ctx.canvas.height;
var yd=30;
var x0=yd;
var y0 = Math.floor(canvasH-yd);
ctx.beginPath();
ctx,moveTo(x0,y0);
ctx.lineTo(canvasW-x0,y0);
ctx.strokeStyle="#eee";
ctx.stroke();
ctx.beginPath();
ctx,moveTo(x0,y0);
ctx.lineTo(x0,yd);
ctx.strokeStyle="#eee";
ctx.stroke();
ctx.beginPath();
for (var i = 0; i < 5; i++) {
ctx.moveTo(x0, y0-space * i - 0.5);
ctx.lineTo(canvasW, y0-space * i - 0.5);
ctx.strokeStyle = "#000";
ctx.stroke();
}
for(var i = 0; i < 5; i++) {
ctx.moveTo(x0-6, y0-space * i - 0.5);
ctx.lineTo(x0, y0-space * i - 0.5);
ctx.strokeStyle = "#eee";
ctx.stroke();
ctx.font="12px 微软雅黑";
ctx.textAlign="right";
ctx,textBaseline="middle";
ctx.fillStyle="#000";
ctx.fillText(100*i,x0-6,y0-space*i);
}
var arr=[
{
x:"Mon",
y:10
},
{
x:"Tue",
y:60
},
{
x:"Wed",
y:200
},
{
x:"Thu",
y:340
},
{
x:"Fri",
y:380
},
{
x:"Sat",
y:340
},
{
x:"Sun",
y:220
}
]
ctx.beginPath();
ctx.moveTo(x0,y0);
for(var i=0;i<arr.length;i++){
ctx.moveTo(x0+space*(i+1),y0);
ctx.lineTo(x0+space*(i+1),y0+6);
ctx.strokeStyle="#000";
ctx.stroke();
ctx.font="16px 微软雅黑";
ctx.textAlign="center";
ctx.textBaseline="top";
ctx.fillStyle="#000";
ctx.fillText(arr[i].x,x0+space*(i+1),y0+6);
ctx.fillStyle="#6495ed";
ctx.fillRect(x0+space*(i+1)-30,y0-arr[i].y,60,arr[i].y);
ctx.textBaseline="top";
ctx.fillStyle="#6495ed";
}
</script>
</html>
以上是关于柱状图的主要内容,如果未能解决你的问题,请参考以下文章