2012-10-21 55 views
1

所以我正在嘗試使用畫布編寫一個簡單的精靈加載方法,並且我發現了一個可怕的刷新率。這是我正在使用的繪製方法。在HTML中使用畫布處理精靈加載

function DrawSprite(context, 
       drawX, 
       drawY, 
       drawH, 
       drawW, 
       spriteXIndex, 
       spriteYIndex, 
       spriteW, 
       spriteH, 
       image){ 
    var imageObj = new Image(); 
    imageObj.onload = function() { 
     //draw cropped image 
     var sourceX = (spriteXIndex * spriteW); 
     var sourceY = (spriteYIndex * spriteH); 

     context.drawImage(imageObj, sourceX, sourceY, spriteW, spriteH, drawX, drawY, drawW, drawH); 
    }; 
    imageObj.src = image; 

}

當過這個叫我得到的圖像的一個非常明顯的重繪。我想過一些解決方案,但我不確定實現它們的最佳方法。首先是雙緩衝區。但我不知道如何實現,而不是創建第二個畫布,並在底下繪製它並使用z-index處理交換。另一個是存儲圖像,而不是每次我想繪製一個精靈時重新創建它。我將首先嚐試第二種方法,並在啓動程序之前預先加載圖像,但我希望能夠提供有關處理此問題的最佳方法的輸入信息。

回答

2

你似乎在做的是創建一個新的圖像,並從源碼每次加載它肯定會導致性能問題。處理它的最好方法是一旦保存並重新使用它就加載圖像。下面是一個非常簡單的例子。小提琴是在裝載部分稍微更復雜,因爲林從服務http://retroships.com

function Sprite(options){ 
    this.load(options.imagePath); 
    this.x = 0; 
    this.y = 50; 
    this.isLoaded = false; 
} 

Sprite.prototype.load = function(imagePath){ 
    this.image = new Image(); 
    var that = this; 

    this.image.src = imagePath; 

    this.image.onload = function(){ 
     that.isLoaded = true; 
    } 
} 

Sprite.prototype.draw = function(){ 
    ctx.drawImage(this.image, this.x, this.y); 
} 

// to use, you can pass other params and handle them like x/y/width/height what have you. 
var yourSprite = new Sprite({imagePath : "pathtoimage.png"}); 

function render(){ 
    if(yourSprite.isLoaded){ 
     canvasContext.drawImage(yourSprite.image, yourSprite.x, yourSprite.y); 
    } 
} 

Working Demo

加載圖像