2013-07-23 12 views
3
function Background() { 
    this.speed = 1; // Redefine speed of the background for panning 

    // Implement abstract function 
    this.draw = function() { 
     // Pan background 
     this.y += this.speed; 
     this.context.drawImage(imageRepository.background, this.x, this.y); 

     // Draw another image at the top edge of the first image 
     this.context.drawImage(imageRepository.background, this.x, this.y - this.canvasHeight); 

     // If the image scrolled off the screen, reset 
     if (this.y >= this.canvasHeight) 
      this.y = 0; 
    }; 
} 

我想了解上面的代碼,它給出了在無限循環中渲染背景圖像的邏輯(給出連續平移的錯覺)。負面座標如何在HTML5畫布中工作?

我無法理解下面一行:

this.context.drawImage(imageRepository.background, this.x, this.y - this.canvasHeight); 

顯然this.y - this.canvasHeight永遠> 0如何負y座標由帆布解釋?或者簡單地說,下面的代碼會做什麼?

ctx.drawImage(img, 0, -10); 
+2

它從基於原點的y位置開始在-10處開始繪製。即:假設y軸上10個像素的默認原點(左側,頂部)不可見,或者您可以將其視爲在屏幕上10個像素處開始y。 – dc5

+0

@ dc5 +1相當正確。另外,如果偏移量太大以至於不能在屏幕上繪製任何圖像,則有證據表明,某些瀏覽器根本無法渲染圖像以獲得性能。 – markE

+0

@ dc5感謝了。 –

回答

5

它從-10開始,根據原點繪製y位置。

也就是說:假設y軸上10個像素的默認原點爲0,0(左上角)將不可見,或者您可以將其視爲在屏幕上10像素處開始y。

+1

任何方式使它可見使用負座標作爲邊距? –