需求
根据圆心坐标和圆半径生成一组圆内随机坐标
代码
/**
* 根据圆心坐标生成一组圆内随机坐标
* @param {number} radius 半径
* @param {number} centerX 圆心x轴坐标
* @param {number} centerY 圆心y轴坐标
* @return {Array} 坐标数组
*/
getRandomCoordinatesInCircle(radius, centerX, centerY){
let coords = [];
const num = 10; // 生成坐标数量。
while(coords.length < num) {
let x = (Math.random() * radius * 2 - radius + centerX).toFixed(5);
let y = (Math.random() * radius * 2 - radius + centerY).toFixed(5);
// x^2 + y^2 <= r^2
let distance = Math.sqrt(Math.pow(x - centerX, 2) + Math.pow(y - centerY, 2));
if (distance <= radius) {
const currentPoint = [x, y];
if (!coords.includes(currentPoint)) {
coords.push(currentPoint);
}
}
}
return coords;
}