2014-04-08 26 views
0

我做了這個小小的腳本,使圖像反彈(這是工作正常)。幾個畫布對象的實例

現在我試圖在畫布上添加更多圖片(該對象的更多實例),但由於某些原因,它仍然只顯示一個。

如果有人可以發現我錯過了什麼,它將不勝感激。

var img = function() { 

    this.props = { 
     x: Math.floor(Math.random() * W + 1), 
     y: 50, 

     radius: 40, 

     // Velocity 
     vy: 1, 

     // angle 
     angle: 0, 
     direction: 1 
    }; 

    var self = this; 

    this.draw = function() { 
     ctx.drawImage(im, self.props.x, self.props.y); 
    }, 

    this.update = function() { 
     ctx.clearRect(0, 0, W, H); 

     self.draw(); 

     self.props.y += self.props.vy; 
     self.props.vy += gravity; 

     if(self.props.y + self.props.radius > H) { 
      self.props.y = H - self.props.radius; 
      self.props.vy *= -bounceFactor; 
      self.props.direction *= -1; 
     } 
    }; 

}; 

// my instances 
var el = new img(); 
var el2 = new img(); 
var el3 = new img(); 

function main() { 
    el.update(); 
    el2.update(); 
    el3.update(); 
} 

setInterval(main, 1000/60); 

下面是完整的代碼:FIDDLE

回答

1

您清除所有車輛的畫布,因此只顯示最後一個車輛。
只需在main()函數中清除一次即可。

+0

就是這樣!謝謝! – Skwal

0

你在DOM使用單個圖像實例...您的提琴使用src從封閉範圍指的是單個圖像實例。

編輯:在你的代碼中,這裏im實際上並不是指什麼,但它在img()的所有實例中共享。

+0

這是因爲所有的圖像都有相同的來源。沒有錯。 – Skwal

+0

但是在你的小提琴中有'src = document.getElementById('img')',因此訪問包含圖像的DOM元素而不是其源。我對畫布不太熟悉,但您有幾個實例共享一個數據源。如果沒關係,我很好;) – cepharum