1、确定纵坐标的范围并绘制

2、根据真实数据绘制折线

# 确定纵坐标的范围并绘制

``````(5, 34.1)  => (10, 40)
(10, 34)   => (10, 40)
(-5.1, 40) => (-10, 40)``````
``````// 确定Y轴取值范围
function findRange (num, type, limit) {
limit = limit || 10;

// upper向上查找，lower向下查找
type = type ? type : 'upper';

// 进行取整操作，避免while时进入死循环
if (type === 'upper') {
num = Math.ceil(num);
} else {
num = Math.floor(num);
}
while (num % limit !== 0) {
if (type === 'upper') {
num++;
} else {
num--;
}
}

return num;
}``````

``````opts = {
...
series: [{
...
data: [15, 20, 45, 37, 4, 80]
}, {
...
data: [70, 40, 65, 100, 34, 18]
}
]
}``````

``````// 合并数据，将series中的每项data整合到一个数组当中
function dataCombine(series) {
return series.reduce(function(a, b) {
return (a.data ? a.data : a).concat(b.data);
}, []);
}

// 根据数据范围确定最小单位刻度
function getLimit (maxData, minData)
var limit = 0;
var range = maxData - minData;
if (range >= 10000) {
limit = 1000;
} else if (range >= 1000) {
limit = 100;
} else if (range >= 100) {
limit = 10;
} else if (range >= 10) {
limit = 5;
} else if (range >= 1) {
limit = 1;
} else if (range >= 0.1) {
limit = 0.1;
} else {
limit = 0.01;
}
}

var dataList = dataCombine(opts.series);
// 获取传入数据的最小值
var minData = Math.min.apply(this, dataList);
// 获取传入数据的最大值
var maxData = Math.max.apply(this, dataList);

var limit = getLimit(maxData, minData);

var minRange = findRange(minData, 'lower', limit);
var maxRange = findRange(maxData, 'upper', limit);``````

``````function findRange (num, type, limit) {
limit = limit || 10;
type = type ? type : 'upper';
var multiple = 1;
while (limit < 1) {
limit *= 10;
multiple *= 10;
}
if (type === 'upper') {
num = Math.ceil(num * multiple);
} else {
num = Math.floor(num * multiple);
}
while (num % limit !== 0) {
if (type === 'upper') {
num++;
} else {
num--;
}
}

return num / multiple;
}``````

Y轴效果图：

``````opts = {
...
series: [{
...
data: [15, 20, 45, 37, 4, 80]
}, {
...
data: [70, 40, 65, 100, 34, 18]
}
]
}``````

``````opts = {
...
series: [{
...
data: [0.15, 0.2, 0.45, 0.37, 0.4, 0.8]
}, {
...
data: [0.30, 0.37, 0.65, 0.78, 0.69, 0.94]
}
]
}``````

# 根据真实数据绘制折线

``````config = {
xAxisHeight: 30, // X轴高度
yAxisWdith: 30   // Y轴宽度
}``````
``````var data = [15, 20, 45, 37, 4, 80];
var xPoints = [];
var validWidth = opts.width - config.yAxisWidth;
var eachSpace = validWidth / opts.categories.length;
var start = config.yAxisWidth;

data.forEach(function (item, index) {
xPoints.push(start + (index + 0.5) * eachSpace);
});``````

`y`坐标稍微会复杂一点，需要根据Y轴的范围已经本身的数值进行计算得出。

``````y = validHeight * (data - min) / (max - min);
// 由于canvas画布是左上角为原点坐标，故我们变化一下
// 得到最终的y绘制点
y = valideHeight - y;``````

``````var data = [15, 20, 45, 37, 4, 80];
var yPoints = [];
var validHeight = opts.height - config.xAxisHeight;
data.forEach(function(item) {
var y = validHeight * (item - min) / (max - min);
y = validHeight - y;

yPoints.push(y);
}``````

17 人关注
5 篇文章