大家好,我是梦辛工作室的灵,最近又开始制作数据统计类软件了,本想偷偷懒用e-chart,可无奈e-chart的微信小程序版和设计图的差异太多,没办法,还是得靠自己,就只有自己撸代码了=-=,老规矩先上效果图:
看着还行吧,其实也不难,就是按照比例绘制几个长方体,然后最好记录下每个长方体的开始和结束坐标,可用于计算点击位置,下面看代码:
function drawZhuChart(that){
let width = app.globalData.width; //手机宽度
let height = app.globalData.height; //手机高度
let rectWidth = width * 0.65; //定义长方快最长长度
let rectHeight = 20; //定义长方块高度
let spaceHeight = 5; //定义每个长方块的间距
let data = [ //绘图数据
{
name:"图书馆",
pre:80, //所占百分比
count:20 //数量
},
{
name:"图书馆",
pre:100,
count:80
},
{
name:"图书馆",
pre:20,
count:10
},
{
name:"图书馆",
pre:10,
count:50
},
];
let ctx = wx.createCanvasContext('zchart');
ctx.setTextAlign("left");
ctx.setTextBaseline('middle');
ctx.setFontSize(12);
let curDataLocation = [];
for(var x in data){
ctx.setFillStyle("#50D2C2");
let startPoint = { //计算每个数据的起点
x:0,
y:x * (rectHeight + spaceHeight),
}
//填充画布
ctx.fillRect(startPoint.x,startPoint.y,rectWidth * data[x].pre / 100 ,rectHeight);
ctx.setFillStyle("#000000");
//计算文字坐标
let textSize = {
x:startPoint.x + rectWidth * data[x].pre / 100 + spaceHeight,
y:startPoint.y + rectHeight / 2
}
ctx.fillText(data[x].name + " " + data[x].count , textSize.x,textSize.y);
//捕捉每组 数据,便于计算点击时是点击的哪个模块
curDataLocation.push({
start:startPoint,
end:{
x:startPoint.x + rectWidth,
y:startPoint.y + rectHeight
},
data:data[x]
});
}
ctx.draw();
that.data.curDataLocation = curDataLocation;
}