javascript - If 语句不起作用 (Javascript)

标签 javascript if-statement canvas

我有一个代码,如果它在 y=x 线上方,则将点分类为 1,如果在 y=x 线下方,则分类为 -1。我在 y=x 的 Canvas 中画线(因为 y 轴在 Canvas 中倒置,所以看起来像 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();
  }
}

然后我在浏览器中运行它,我得到了这个: What I see in the browser

它似乎有点工作,但不完全?

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

请帮忙,谢谢!

最佳答案

您可以将黄线绘制到所需的 x === y 而不仅仅是 Canvas 的末尾。

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

关于javascript - If 语句不起作用 (Javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48850441/

相关文章:

arrays - Excel - 带有 IF 函数的列表中的模态值

javascript - 使用 jQuery 在表单提交上将隐藏输入值设置为 dataURL

css - 拖动鼠标时在 HTML5 Canvas 上更改光标

javascript - 将对象转为数组,将对象添加为新元素

if-statement - 带 then 子句的 If 语句 (LISP)

javascript - POST 请求可以接受两个回调吗?第一个回调可以将数据传递给第二个回调吗?

java - 井字棋决定平局

javascript - 在 Canvas 中变换以在移动时将 Sprite 保持在正确的位置

javascript - 将值替换为 ng-repeat 中的 API 值

javascript - 递归搜索 JSON 对象中的属性名称 {String} 并返回关联值