Javascript 基于阵列的圆交点检测

Javascript 基于阵列的圆交点检测,javascript,arrays,canvas,Javascript,Arrays,Canvas,我有一块画布,我可以在上面单击任何地方放置圆圈。我想检测任意两个圆何时相交,所以我将坐标存储在一个数组中 每个圆的半径是30,所以这只是硬编码到我的公式中。也就是说,即使我把两个放在一起,它也不会触发我的小filltext让我知道它在工作。我试过很多东西。如果有人能告诉我为什么这不起作用,那将是值得赞赏的。我放置圆点的部分工作得很好;我只需要检测重叠 window.onload = init; function init() { var canvas = document.getEle

我有一块画布,我可以在上面单击任何地方放置圆圈。我想检测任意两个圆何时相交,所以我将坐标存储在一个数组中

每个圆的半径是30,所以这只是硬编码到我的公式中。也就是说,即使我把两个放在一起,它也不会触发我的小filltext让我知道它在工作。我试过很多东西。如果有人能告诉我为什么这不起作用,那将是值得赞赏的。我放置圆点的部分工作得很好;我只需要检测重叠

window.onload = init;

function init() {
    var canvas = document.getElementById("testCanvas");
    var context = canvas.getContext("2d");
    var newPath = false;

    var circles = [];
    canvas.onmousedown = function(e) {
        newPath = true;

        x = e.clientX - e.target.offsetLeft;
        y = e.clientY - e.target.offsetTop;
        context.moveTo(x, y);

        context.beginPath();
        context.arc(x, y, 30, 0, 2 * Math.PI, true);
        var nextColor = randomColor();
        context.fillStyle = nextColor; 
        context.fill();
        var aCircle = [x, y];

        function isIntersect(aCircle, circle) {
            return Math.sqrt((aCircle[0]-circle.x) ** 2 + (aCircle[1] - circle.y) ** 2) < 30;
          };

        circles.forEach(circle => {
            if (isIntersect(aCircle, circle)) {
                context.fillText('INTERSECTED', 60, 160);
            }
        });

        circles.push(aCircle);

        context.closePath(); 


    }
}
window.onload=init;
函数init(){
var canvas=document.getElementById(“testCanvas”);
var context=canvas.getContext(“2d”);
var newPath=false;
var循环=[];
canvas.onmousedown=函数(e){
newPath=true;
x=e.clientX-e.target.offsetLeft;
y=e.clientY-e.target.offsetTop;
上下文。移动到(x,y);
context.beginPath();
弧(x,y,30,0,2*Math.PI,true);
var nextColor=randomColor();
context.fillStyle=nextColor;
context.fill();
var aCircle=[x,y];
函数isIntersect(圆形、圆形){
返回数学sqrt((aCircle[0]-circle.x)**2+(aCircle[1]-circle.y)**2)<30;
};
圆。forEach(圆=>{
if(isIntersect(圆形、圆形)){
context.fillText('INTERSECTED',60,160);
}
});
圆。推(一圈);
closePath();
}
}

将半径乘以2,因为每个圆都有一个

window.onload=init;
函数init(){
var canvas=document.getElementById(“testCanvas”);
var context=canvas.getContext(“2d”);
var newPath=false;
var循环=[];
canvas.onmousedown=函数(e){
newPath=true;
x=e.clientX-e.target.offsetLeft;
y=e.clientY-e.target.offsetTop;
上下文。移动到(x,y);
context.beginPath();
弧(x,y,30,0,2*Math.PI,true);
var nextColor='#123123'//randomColor();
context.fillStyle=nextColor;
context.fill();
var aCircle=[x,y];
函数isIntersect(圆形、圆形){
var半径=30;
var dist=Math.hypot(A圆[0]-圆[0],A圆[1]-圆[1]);
返回区{
if(isIntersect(圆形、圆形)){
console.log(“intresected”);
//context.fillText('INTERSECTED',0,0);
}
});
圆。推(一圈);
closePath();
}
}

aCircle
正在使用数组索引,但是
circle
正在使用
x
y
属性。正在生成的圆应该使用数组索引(第21行)。此外,我认为交叉条件应该是
,我不敢相信它是如此之小。我已经忽略了几个小时了。谢谢,关于30。好主意。提示:不要花几个小时看代码。只需使用调试器检查您使用的每个值,您就会发现一个
未定义的