利用画布绘制柱状图
<!DOCTYPE html> <head> <meta charset="utf-8" /> <title>柱状图</title> <style>/*绘制画布的样式*/ canvas{ background-color: rgb(243,243,243); } </style> </head> <body> <canvas width="800px" height="500px"></canvas><!--绘制一个画布--> <script> // 获取画布对象和画布工具 var maycanvas=document.querySelector("canvas"); var ctx=maycanvas.getContext("2d"); // 动态获取画布的宽和高 var canvasW=ctx.canvas.width; var canvasH=ctx.canvas.height; // 定义变量 var unm=50; // 绘制x,y轴 ctx.moveTo(unm,unm); ctx.lineTo(unm,canvasH-unm); ctx.lineTo(canvasW-unm,canvasH-unm) ctx.strokeStyle="#000000"; ctx.stroke(); // 绘制y轴突出部位和下标 for(i=0;i<5;i++){ ctx.moveTo(unm,canvasH-unm-i*100); ctx.lineTo(unm-10,canvasH-unm-i*100) ctx.strokeStyle="#000000"; ctx.stroke(); ctx.fillText(i*100,unm-30,canvasH-unm-i*100) } // 绘制x轴和下标 for(i=1;i<7;i++){ ctx.moveTo(unm+40+80*i,canvasH-unm); ctx.lineTo(unm+40+80*i,canvasH-unm+10); ctx.strokeStyle="#000000"; ctx.stroke(); } // 绘制柱形 ctx.beginPath(); ctx.moveTo(unm+40,canvasH-unm); ctx.lineTo(unm+40,canvasH-unm+10); ctx.strokeStyle="#000000"; ctx.stroke(); var arr=[20,70,200,330,390,320,230]; for(i=0;i<8;i++){ ctx.fillStyle="rgb(51,152,219)"; ctx.rect(unm+20+80*i, canvasH-unm-arr[i],40,arr[i]); ctx.fill(); } //添加下面的字 var zi=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"] ctx.beginPath(); for(i=0;i<zi.length;i++){ ctx.fillText(zi[i],80+i*80,canvasH-30) } </script> </body>