我正在尝试在我正在制作的游戏中在画布上生成小兵 . creeps应该以四种随机模式(x的开始,y的开始,x的结束,y的结束)在画布边框上产生,并且来自canvas.height或canvas.width的相应x或y的随机值 . 代码将更好地解释我认为:
//Creep Array- Creep() gets pushed into it later
var creeps = []
//Random position generation
function Creep() {
this.XorY = Math.floor(Math.random() * 4)
console.log("Creep.XorY "+ this.XorY);
if (this.XorY==0) {
this.x=10
this.y=Math.floor(Math.random()*canvas.height)
}
//.....
}
//function Creep() continues with more if conditionals for spawn at X or Y axis
// I am getting error that the property height of undefined in anonymous function
// Creep cannot be read. This is I think related to the canvas but the canvas var
// is declared at the top and defined later in the script as follows:
window.onload = function() {
// Nastavenie premennych
button = document.getElementById("button")
text = document.getElementById("text")
canvas = document.getElementById("canvas")
ctx = canvas.getContext("2d")
requestAnimationFrame(mainLoop);
}
我使用随机函数错误或我的代码流是否有问题?我使用画布宽度和高度属性来绘制我的船,这似乎工作正常 .
1 回答
看起来你正试图在
Creep()
函数中使用canvas
节点的height
,但实际上你实际上是在代码中定义了canvas
节点 .因此,当JavaScript尝试读取
canvas.height
值时,canvas
尚未定义,因为它将在页面完成加载后定义(window.onload) .在定义
Creep()
函数之前尝试放置var canvas = document.getElementById("canvas");
.