数据展示-条形图-canvas

xiaoxiao2021-02-28  107

假设后台要求实现一个条形图,而且还是动态生成,(此处暂时不考虑用户输入数值,仅考虑数据从后台生成); 大概效果如图: 比如在500*500的框内生成;以下是基本布局,

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>trialgame</title> <style> * { margin: 0; padding: 0 } canvas { margin: 0; padding: 0; background: #ddd; } </style> </head> <body> <canvas id="cloth" width="500" height="500"></canvas> <button id="btn">开始</button> <script> //此处写代码 </script> </body> </html>

首先,每一个矩形框就是具有位置(横纵坐标)高度宽度这四个属性;这样只要new rec,那么这个变量就会具有位置和高度等属性;

var rec = function (x, y, w, h) { this.x = x; this.y = y; this.w = w; this.h = h; }

其次,生成矩形框需要有一个方法,我选择增加给rec,(矩形颜色为京东红,默认未考虑兼容性;考虑兼容性也不难),

rec.prototype.draw = function () { var ctx = document.getElementById("cloth").getContext("2d"); ctx.fillStyle = "#e4393c"; ctx.rect(this.x, this.y, this.w, this.h); ctx.fill() }

假设后台传过来50 100 150等比增加的数据;这里用全局变量y代替;为了性能,防止用户狂点,这里定义全局变量timer;

var y=50; var timer=null;

最后定义点击事件,这里假设只有9条数据,

btn.onclick= function (){ clearInterval(timer); timer=setInterval(function () { if(y<500){ console.log("y:"+y); var x = new rec(y - 30, 500 - y, 30, y); x.draw(); y+=50 }else{ clearInterval(timer); console.log(y); } }, 1000) }

以上就达到效果了; 真正从后台传过来的数据; 一般是json格式,也可以处理,但那不是今天要讲的内容; 以下是完整代码:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>trialgame</title> <style> * { margin: 0; padding: 0 } canvas { margin: 0; padding: 0; background: #ddd; } </style> </head> <body> <canvas id="cloth" width="500" height="500"></canvas> <button id="btn">开始</button> <script> var rec = function (x, y, w, h) { this.x = x; this.y = y; this.w = w; this.h = h; } rec.prototype.draw = function () { var ctx = document.getElementById("cloth").getContext("2d"); ctx.fillStyle = "#e4393c"; ctx.rect(this.x, this.y, this.w, this.h); ctx.fill() } var y=50; var timer=null; btn.onclick= function (){ clearInterval(timer); timer=setInterval(function () { if(y<500){ console.log("y:"+y); var x = new rec(y - 30, 500 - y, 30, y); x.draw(); y+=50 }else{ clearInterval(timer); console.log(y); } }, 1000) } </script> </body> </html>
转载请注明原文地址: https://www.6miu.com/read-71560.html

最新回复(0)