gpt4 book ai didi

javascript - 使用随机/数组生成的坐标创建 Canvas 线。不工作,为什么?

转载 作者:行者123 更新时间:2023-11-28 08:17:19 25 4
gpt4 key购买 nike

我不明白为什么 Canvas 线的坐标没有使用数组进行消化:有什么建议吗?

我正在尝试为随机生成的线组创建一种算法,这些线组最终从最后一条线结束的地方链接在一起。就像一条蛇,只要你愿意,它就会变得更长。

     var c = document.getElementById("playground");
var ctx = c.getContext("2d");

//global scope
var i;
var c1 = []; //c is short for collect
var c2 = [];
var c3 = [];
var c4 = [];

var initiate = function(){ //the buttom that triggers the program


var clock = function(){

/* if(i){
alert(i);
}*/

i+=1; //increment each time the..
//function gets called.

var a = Math.round(Math.random()*200);
var b = Math.round(Math.random()*200);
var c = Math.round(Math.random()*200);
var d = Math.round(Math.random()*200);
c1.push(a);
c2.push(b);
c3.push(c);
c4.push(d);


ctx.beginPath();
ctx.moveTo(c1[i], c2[i]); //Here is where the issue seems to be? they don't run.
ctx.lineTo(c3[i], c4[i]);
ctx.stroke();

//if(c1.length===10){
//alert(c1);
//}

}; //end of clock

setInterval(clock,80);



}; //end of parent function

最佳答案

您正在将 i 初始化为 var i;。当您递增它时,它会导致 NaN,因此只需将其初始化为 var i = 0; 或类似的即可。

编辑:另外,为什么你的问题出现在该行是因为你试图访问数组的第 NaN 个元素,这是 JavaScript 不喜欢的。

关于javascript - 使用随机/数组生成的坐标创建 Canvas 线。不工作,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23451781/

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