【问题标题】:Handling sprite loading using canvas in HTML在 HTML 中使用画布处理精灵加载
【发布时间】:2012-10-11 06:10:33
【问题描述】:

所以我正在尝试使用画布编写一个简单的精灵加载方法,但我注意到刷新率很糟糕。这是我正在使用的绘制方法。

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 处理交换之外,我不确定如何实现它。另一个是存储图像而不是每次我想绘制精灵时都重新创建它。我将首先尝试第二种方法并在启动程序之前预加载图像,但我希望输入有关处理此问题的最佳方法的信息。

【问题讨论】:

    标签: javascript html canvas


    【解决方案1】:

    您似乎在做的是创建一个新图像并每次都从源加载它,这肯定会导致性能问题。处理它的最佳方法是在保存后加载图像并重新使用它。下面是一个非常简单的例子。加载部分的小提琴有点复杂,因为我从服务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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-23
      • 2014-04-28
      • 2011-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多