gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 17:46:38 25 4
gpt4 key购买 nike

我有一个代码,如果它在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com