背景:
最近需要开发一个新需求,需要绘制一个随机生成数字的散点图,要求点与点的距离要大于某个特定值。
解决思路:
通过循环获取每个坐标点,每获取一个新的坐标点,都要与之前生成的坐标点进行对比,如果大于指定距离,
则符合条件,退出循环,如果小于或等于该距离,则继续随机生成,进行比对。
实现代码:
let dataArray = [];
for (let i = 1; i < 10; i++) {
let obj = {};
if (i == 0) {
obj.x = Math.round(Math.random() * 100);
obj.y = Math.round(Math.random() * 100);
} else {
let number = 0;
while (number <= 10) {
obj.x = Math.round(Math.random() * 100);
obj.y = Math.round(Math.random() * 100);
let flag = dataArray.every((item) => {
//点与点之间的计算公式
number = Math.sqrt(Math.pow(Math.abs(obj.x - item.x), 2) + Math.pow(Math.abs(obj.y - item.y), 2));
return number >= 10
})
if (flag) {
break
}
}
}
dataArray.push(obj);
}
console.log(dataArray)
配合echarts完整代码实现:
可直接复制到本地看效果!!!!
<!DOCTYPE html>
<html lang="zh-CN" style="height: 100%">
<head>
<meta charset="utf-8">
</head>
<body style="height: 100%; margin: 0">
<div id="container" style="height: 100%"></div>
<script type="text/javascript" src="https://fastly.jsdelivr.net/npm/echarts@5.4.0/dist/echarts.min.js"></script>
<script type="text/javascript">
var dom = document.getElementById('container');
var myChart = echarts.init(dom, null, {
renderer: 'canvas',
useDirtyRect: false
});
var app = {};
var option;
let dataArray = [];
for (let i = 1; i < 10; i++) {
let obj = {};
if (i == 0) {
obj.x = Math.round(Math.random() * 100);
obj.y = Math.round(Math.random() * 100);
} else {
let number = 0;
while (number <= 10) {
obj.x = Math.round(Math.random() * 100);
obj.y = Math.round(Math.random() * 100);
let flag = dataArray.every((item) => {
//点与点之间的计算公式
number = Math.sqrt(Math.pow(Math.abs(obj.x - item.x), 2) + Math.pow(Math.abs(obj.y - item.y), 2));
return number >= 10
})
if (flag) {
break
}
}
}
dataArray.push(obj);
}
console.log(dataArray)
let newArray = []
dataArray.map((ele) => {
let array = []
array.push(ele.x);
array.push(ele.y);
newArray.push(array);
})
option = {
xAxis: {},
yAxis: {},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross'
}
},
series: [
{
symbolSize: 20,
data: newArray,
type: 'scatter'
}
]
};
if (option && typeof option === 'object') {
myChart.setOption(option);
}
window.addEventListener('resize', myChart.resize);
</script>
</body>
</html>