如果语句不起作用(JavaScript)

Plzhelp

我有一个代码将点1如果在线y = x之上,则将其分类;如果点在线y = x之下,则将-1分类。我在y = x的画布上画线(由于y轴在画布上是倒置的,因此看起来像y = -x)。然后绘制每个点,如果是1,则将其绘制为绿色,如果为-1,则将其绘制为红色。我希望看到一条直线,一侧为绿色,另一侧为红色。我运行了代码,结果很奇怪。

这是我如何标记我的观点的代码:

function Point(x, y){
    this.x = x;
    this.y = y;
    this.label = 0;
    if(this.y >= this.x){
        this.label = 1;
        console.log(x, y, "UP");
    }else if(this.y < this.x){
        this.label = -1;
        console.log(x, y, "Down");
    }
}

这是画点的代码:

function draw(){
  ctx.clearRect(0, 0, can1.width, can1.height);
  ctx.strokeStyle = "yellow";
  ctx.beginPath();
  ctx.moveTo(0, 0);
  ctx.lineTo(can1.width, can1.height);
  ctx.stroke();
  ctx.closePath();
  for(var i = 0; i < points.length; i++){
    var x = points[i].x;
    var y = points[i].y;
    if(points[i].label == 1){
        var color = "Chartreuse";
    }else{
        var color = "red";
    }
    ctx.fillStyle = color;
    ctx.beginPath();
    ctx.arc(x, y, 5, 0, Math.PI * 2, false);
    ctx.fill();
    ctx.closePath();
  }
}

然后,我在浏览器中运行它,我得到了: 我在浏览器中看到的

这似乎是可行的,但还不够充分?

编辑:x和y值是在代码的其他部分中随机分配的。

请帮忙,谢谢!

妮娜·斯科茨(Nina Scholz)

您可以在需要的地方绘制黄线x === y,而不仅仅是在画布的末端。

ctx.lineTo(Math.min(can1.width, can1.height), Math.min(can1.width, can1.height));

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章