Javascript isPointInPath 条件

Javascript isPointInPath conditions

我有一个 canvas 有不同的形状会改变颜色,我想检查点击形状的玩家是否与另一个形状的颜色相匹配,如果为 true 则可以增加分数,但它不会如果我删除了 && one==flr 部分,它就可以工作 这是随机化颜色和添加形状的代码

function interval()
{
mycanvas = document.getElementById("mycanvas");
    var clr=["red", "blue", "green", "yellow"];
    var one=[Math.floor((Math.random() * 4) + 0)];
    var two=[Math.floor((Math.random() * 4) + 0)];
    var thr=[Math.floor((Math.random() * 4) + 0)];
    var flr=[Math.floor((Math.random() * 4) + 0)];  
    var t=1000;  
    var score=0;

ctx.fillStyle=clr[one];
    ctx.fillRect(300,250,150,250);
    ctx.fillStyle=clr[two];
    ctx.fillRect(700,250,150,250);
    ctx.fillStyle=clr[thr];
    ctx.fillRect(1100,250,150,250);

    ctx.beginPath();
    ctx.moveTo(300,500);
    ctx.lineTo(1250,500);
    ctx.lineTo(1450,720);
    ctx.lineTo(100,720);
    ctx.closePath();
    ctx.fillStyle=clr[flr];
    ctx.fill();
    ctx.strokeStyle="black";
    ctx.stroke();

检测鼠标点击的代码

mycanvas.onclick= function(e) 
    { 

        var pos=this.getBoundingClientRect(), x=e.clientX - pos.left,
        y = e.clientY - pos.top;
        getRect(300,250,150,250);
        if (ctx.isPointInPath(x,y) && one == flr) 
        {
            score+=10;
        }
        else
        delay=delay-100; 
    };

    if(delay<=0)
    {   
        clearInterval(intervalID);
    }
    function getRect(x,y,w,h)
    {
        ctx.beginPath();
        ctx.rect(x,y,w,h);
        ctx.closePath();
    }
}

您正在使用 Math.random() 生成 oneflrMath.random() 在这两种情况下都会生成一个随机数,并且这两个数字不会总是相等。

var one=[Math.floor((Math.random() * 4) + 0)];
var flr=[Math.floor((Math.random() * 4) + 0)];
console.log(one);
console.log(flr);

另一件事是你将这两个作为数组,你不能只使用 == 比较数组。即使这两个相等,您的条件仍然为假。

var one=[1];
var flr=[1];
console.log(one==flr);

你必须比较然后使用索引或在将它们转换为字符串之后像这样

var one=[1];
var flr=[1];
console.log(one[0]==flr[0]);
console.log(JSON.stringify(one) == JSON.stringify(flr));//if more than one value use this