我有问题。每当我尝试创建Candy函数的对象时,所有属性似乎都可以正常创建。但是,每当我尝试运行draw函数时,都会使用最新创建的对象的所有属性,而不是我正在使用的属性。它总是会绘制我创建的第二个对象,但不会是第一个。我不知道为什么。我已经尝试了一切来尝试解决这个问题,所以如果在这段代码中看起来非常低效,那么这可能是我尝试修复此问题的众多尝试之一。你们知道这个问题吗?
以下是Candy功能的代码:
Candy = function(img, location, canvas) {
self = {}
self.image = new Image()
self.image.src = img
self.location = {x: location.x, y: location.y}
self.canvas = canvas
self.draw = function() {
self.canvas.drawImage(self.image, self.location.x, self.location.y, 132.4, 132.4)
}
self.move = function(FPS, seconds, location) {
frames = FPS * seconds
deltaX = (location.x - self.location.x) / frames
deltaY = (location.y - self.location.y) / frames
counter = 0
setInterval(function() {
self.location.x += deltaX
self.location.y += deltaY
counter++
self.draw()
if(counter >= frames)
clearInterval()
}, 1000 / FPS)
}
self.image.onload = function() {
Candy.list.push(self)
Candy.queue.splice(0, 1)
if(Candy.queue.length == 0)
draw()
else
Candy(Candy.queue[0].img, Candy.queue[0].location, Candy.queue[0].canvas)
}
}
Candy.list = []
Candy.queue = []

这是我称之为Candy功能的地方:
gameStarted = true
Candy.queue.push({img: "client/img/candy.png", location: {x: width / 3 - 87.5, y: height / 10}, canvas: canvasContext})
Candy.queue.push({img: "client/img/candy2.png", location: {x: width / 3 - 87.5, y: 3 * (height / 10)}, canvas: canvasContext})
Candy(Candy.queue[0].img, Candy.queue[0].location, Candy.queue[0].canvas)

最后,这是绘图功能:
function draw() {
colorRect(0, 0, canvas.width, canvas.height, 'white');
colorText("Player 1", 0.02, 0.05, "black", "40px Comic Sans");
colorText("Player 2", 0.88, 0.05, "black", "40px Comic Sans");
if(!gameStarted) {
if(player1.ready)
colorText("Ready", 0.02, 0.09, "green", "20px Comic Sans");
else
colorText("Not Ready", 0.02, 0.09, "red", "20px Comic Sans");
if(player2.ready)
colorText("Ready", 0.88, 0.09, "green", "20px Comic Sans");
else
colorText("Not Ready", 0.88, 0.09, "red", "20px Comic Sans");
if(player1.ready && player2.ready)
colorText("Press a button to start the game!", 0.32, 0.5, "black", "40px Comic Sans")
}else{
alert(Candy.list[0].image.src)
alert(Candy.list[0].getImg())
for(var i = 0; i < Candy.list.length; i++) {
Candy.list[i].draw()
}
//TODO
}
}
&#13;
答案 0 :(得分:0)
好吧,我明白了。在这个函数中,我用这个取代了self,它解决了这个问题。无需任何回复。