<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> body{ text-align: center; } canvas{ background: #ddd; } </style> </head> <body> <canvas id="canvas" width="800" height="700"></canvas> <script src="jquery-3.2.1.js"></script> <script> //获取画笔工具 //创建变量保存画布宽度高度边界距离 //绘制统计图的轮廓 //发送ajax请求数据 //返回数据,动态绘制图形 var elem = document.getElementById("canvas"); var canvas = elem.getContext("2d"); var w= 800,//画布宽度 h = 700,//画布高度 pd = 50 ;//统计图的内容到画布边界的距离 canvas.strokeRect(pd,pd,w-2*pd,h-2*pd); $.ajax({ type:"GET", url:"saledata.php", success:function(data){ console.log("成功接收数据"); console.log(data); //数据个数 //每个柱子/间距宽度 var count = data.length; var barWidth = (w-2*pd)/(2*count+1); for(var i = 0;i<count;i++){ var d = data[i];//第i月份的数量 //柱子的宽度 var bw = barWidth; //柱子的高度 var bh = d.value; //柱子的x var bx = pd +(2*i+1)*barWidth; //柱子的y var by = h-pd-bh; //绘制矩形 //canvas.strokeRect(bx,by,bw,bh); canvas.fillStyle = rColor(); canvas.fillRect(bx,by,bw,bh); } }, error:function(){ alert("网络出现故障,请检查!"); } }); function rColor(){ var r = Math.floor(Math.random()*256); var g = Math.floor(Math.random()*256); var b = Math.floor(Math.random()*256); return `rgb(${r},${g},${b})`; } </script> </body> </html>
<?php header("Content-Type:application/json;charset=utf-8"); $rows = []; /* $rows=[ ["月份"=>"一月","value"=>280], ["月份"=>"二月","value"=>270], ["月份"=>"三月","value"=>380], ["月份"=>"四月","value"=>280], ["月份"=>"五月","value"=>280], ["月份"=>"六月","value"=>210], ["月份"=>"七月","value"=>180], ["月份"=>"八月","value"=>280], ["月份"=>"九月","value"=>200], ["月份"=>"十月","value"=>280], ["月份"=>"十一月","value"=>300], ["月份"=>"十二月","value"=>300] ]; */ $rows[]=["月份"=>"1月","value"=>160]; $rows[]=["月份"=>"2月","value"=>290]; $rows[]=["月份"=>"3月","value"=>220]; $rows[]=["月份"=>"4月","value"=>100]; $rows[]=["月份"=>"5月","value"=>190]; $rows[]=["月份"=>"6月","value"=>170]; $rows[]=["月份"=>"7月","value"=>270]; $rows[]=["月份"=>"8月","value"=>120]; $rows[]=["月份"=>"9月","value"=>250]; $rows[]=["月份"=>"10月","value"=>240]; $rows[]=["月份"=>"11月","value"=>230]; $rows[]=["月份"=>"12月","value"=>210]; echo json_encode($rows); ?>
***********记得添加jquery-3.2.1.js哦