仿小程序數據助手數據頁面之折線圖
昨天微信團隊發布了神器——小程序數據助手,想起自己以前也寫過一個很簡陋的餅圖繪制的demo,那么就再搞點事,畫個折線圖。
1.Line連線、畫空心圓圈
2.描圓圈
3.填充背景色
4.監聽觸摸手勢
5.隨著滑動讀取數據并顯示
說明
1-4點應該不難理解,第5點需要處理手勢滑動的步長,是以天為單位,一天一移動;浮動層跟隨當前日期移動而移動,其位置當處在對側的半屏區域中,比如接近右屏邊緣時,要在浮動層置左。
1.獲取數據
小程序已經開放了統計接口,直接拿真實的數據過來做了。
https://mp.weixin.qq.com/debug/wxadoc/dev/api/analysis.html#日趨勢
以日趨勢數據為例,按照文檔,先取到access_token,再向https://api.weixin.qq.com/datacube/getweanalysisappiddailysummarytrend?access_token=ACCESS_TOKEN請求數據,傳入起始日期做為參數。這里有一個巨坑,只能夠起始入傳同一天,否則,返回時報range過界錯誤。
整理得到的數組數據示例如下
[
{
"ref_date": "20170412",
"session_cnt": 8,
"visit_pv": 49,
"visit_uv": 4,
"visit_uv_new": 1,
"stay_time_uv": 73.75,
"stay_time_session": 36.875,
"visit_depth": 3.25
},
{
"ref_date": "20170413",
"session_cnt": 10,
"visit_pv": 81,
"visit_uv": 8,
"visit_uv_new": 2,
"stay_time_uv": 351.25,
"stay_time_session": 281,
"visit_depth": 3.5
}
...
]
2.畫折線
var data = require('../../data/daily.js');
Page({
data: {
}, //事件處理函數
onLoad: function () { // 畫布高度,與CSS中定義等值
var canvasHeight = 100; // x軸放大倍數
var ratioX = 10; // y軸放大倍數
var ratioY = 2; const context = wx.createCanvasContext('line-canvas');
data.daily.forEach(function(daily, i, array) { // 當前點坐標
var currentPoint = {
x: i * ratioX,
y: canvasHeight - daily.visit_uv_new * ratioY
}; /* 畫折線 */
if (i < array.length - 1) { // 開始
context.beginPath(); // 移動到當前點
context.moveTo(currentPoint.x, currentPoint.y); // 畫線到下個點
context.lineTo((i + 1) * ratioX, canvasHeight - array[i + 1].visit_uv_new * ratioY); // 設置屬性
context.setLineWidth(1); // 設置顏色
context.setStrokeStyle('#7587db'); // 描線
context.stroke();
} /* 畫圓圈 */
});
context.draw();
}
})
寫代碼的過程中,犯一個錯誤,將context.draw();方法放在forEach循環體中了,于是只顯現出最后一段折線,之前的繪制的全被覆蓋了。
效果如圖
3.畫圓圈
畫圓的本質是畫弧,以當前點作為圓心,畫半徑為3的弧;填充為白色背景,要覆蓋折線的拐點。fill()與stroke()分別填充背景與描邊。
/* 畫圓圈 */context.beginPath();
context.arc(currentPoint.x, currentPoint.y, 2, 0, 2 * Math.PI);context.setStrokeStyle(purple);
context.setFillStyle('white');
context.stroke();
context.fill();
效果如圖
4.畫參照線
畫橫線的同時,標上數值。
/* 畫橫向參照線 */
var lineCount = 4;
var estimateRatio = 3;
var ratio = canvasHeight / lineCount; for (var i = 0; i < lineCount; i++) {
context.beginPath();
var currentPoint = {
x: 0,
y: canvasHeight - i * ratio
}; // 移動到原點
context.moveTo(currentPoint.x, currentPoint.y); // 向Y正軸方向畫線
context.lineTo(canvasWidth, canvasHeight - i * ratio); // 設置屬性
context.setLineWidth(1); // 設置顏色
context.setStrokeStyle(gray);
context.stroke(); // 標注數值
context.setFillStyle(gray);
context.fillText((i * ratio / estimateRatio).toFixed(0), currentPoint.x, currentPoint.y);
}
以上代碼中estimateRatio,是估算的一值,因為到目前為止,還沒有計算報表數據中最大的Y值是幾許。
效果如圖
填充紫色背景
目前看起來都是白底,光禿禿一條折線不免單調,因此要填充上從折線與x軸之前的面積區域。
思路是:每畫一段,便自由落體拐頭向下,左往x軸負方向回到上一個的位置,最后與上一個點閉合,于是形成了一個梯形結構,經多次fill()方法填充后,實現了面積圖的效果。
// 豎直往下,至x軸context.lineTo(nextPoint.x, canvasHeight);// 水平往左,至上一個點的在x軸的垂點context.lineTo(currentPoint.x, canvasHeight);// 設置淡紫色context.setFillStyle(lightPurple);// 實現閉合與x軸之前的區域context.fill();
將以上代碼放在畫折線圖forEach循環體的最末。
得到上述最終效果。