直接上源码scale.ts
const snapArray = [0, 2, 5, 10]; //逼近值数组,保证能被2和5整除
const getFactor = (tickInterval: number)=> {
let num = 1;
while(tickInterval > 10 || tickInterval < 1){ //tickInterval在1-10之间才停止循环
tickInterval = tickInterval/10;
num = num * 10
}
return num
}
/**
* 获取逼进值
* @param {number} actNum
* @param {String} math floor 向下逼近 ceil 向上逼近
*/
const snap = (actNum: number, math: string)=> {
let index = math == 'ceil' ? 0 : snapArray.length - 1;
if(math == 'ceil') {
for (let i = 0; i < snapArray.length; i++) {
if (snapArray[i] > actNum) {
index = i;
break
}
}
} else {
for (let i = index; i > 0 ; i--) {
console.log(i);
if (snapArray[i] < actNum) {
index = i;
break;
}
}
}
return snapArray[index] // 返回最接近的数值
}
/**
* 根据传入值 获取该值下的 坐标最大或最小值
* @param {number} tickInterval 坐标区间范围值
* * @param {number} actNumber 传入值
* @param {String} math floor 向下逼近 ceil 向上逼近
*/
export const snapMultiple = (tickInterval: number, actNum: number, math: string)=> {
let num = 0;
if(math == 'ceil') {
while(num < actNum){
num = num + tickInterval
}
return num
} else {
while(num < actNum){
num = num + tickInterval
}
return num - tickInterval
}
}
/**
* 获取坐标轴最大值
* @param {number} max 最大值
* @param {number} min 最小值
* @param {number} tickCount //预设坐标数量
*/
export const getScaleMax = (max: number, min: number, tickCount: number) => {
if ((max - min) < (tickCount - 1) ) {
return max
}
let tickInterval = (max - min) / (tickCount - 1);
const factor = getFactor(tickInterval);
const snapValue = snap(tickInterval / factor, 'floor');
tickInterval = snapValue * factor;
max = snapMultiple(tickInterval, max, 'ceil'); // 向上取tickInterval的整数倍,
return max
}
在视图的地方直接引用
import { getScaleMax } from '@/utils/scale';
const max = getScaleMax(minData, maxData,tickCount); //传入图表数据的最小值和最大值,返回坐标系最大值
const tickCount = 6;
const chart = new Chart({
container: 'c1',
autoFit: true,
height: 390,
});
chart.scale({
dateStr: {
nice: true
},
activeAmount: { //你的坐标key 值
nice: true,
alias: "激活量",
max,
tickCount
},
applyAmount: {
nice: true,
alias: "申请量",
max,
tickCount
},
});
chart.render();