在我的画布中显示我的资源的加载进度

Display the loading progress of my resources in my canvas

本文关键字:我的 加载 显示 布中 资源      更新时间:2023-09-26

我正面临一个问题与画布。不返回任何错误。我试图做一个加载器,加载每一个资源,如图片,声音,视频等,在应用程序开始之前。加载程序必须绘制动态加载的资源数量。但是此时此刻,我的加载器的结果是冻结浏览器,直到它绘制加载的资源总数。

告诉我如果我不清楚:)这是代码:

function SimpleLoader(){
    var ressources ;
    var canvas;
    var ctx; 
    this.getRessources = function(){
        return ressources;
    };
    this.setAllRessources = function(newRessources){
        ressources = newRessources;
    };
    this.getCanvas = function(){
        return canvas;
    };
    this.setCanvas = function(newCanvas){
        canvas = newCanvas;
    };
    this.getCtx = function(){
        return ctx;
    };
    this.setCtx = function(newCtx){
        ctx = newCtx;
    };
};
SimpleLoader.prototype.init = function (ressources, canvas, ctx){
    this.setAllRessources(ressources);
    this.setCanvas(canvas);
    this.setCtx(ctx);
};
SimpleLoader.prototype.draw = function (){
    var that = this;
    this.getCtx().clearRect(0, 0, this.getCanvas().width, this.getCanvas().height);
    this.getCtx().fillStyle = "black";
    this.getCtx().fillRect(0,0,this.getCanvas().width, this.getCanvas().height)
    for(var i = 0; i < this.getRessources().length; i++){
        var data = this.getRessources()[i];
        if(data instanceof Picture){
            var drawLoader = function(nbLoad){
                that.getCtx().clearRect(0, 0, that.getCanvas().width, that.getCanvas().height);
                that.getCtx().fillStyle = "black";
                that.getCtx().fillRect(0,0, that.getCanvas().width, that.getCanvas().height);
                that.getCtx().fillStyle = "white";
                that.getCtx().fillText("Chargement en cours ... " + Number(nbLoad) +"/"+ Number(100), that.getCanvas().width/2, 100 );
            }
            data.img = new Image();
            data.img.src = data.src;
            data.img.onload = drawLoader(Number(i)+1); //Update loader to reflect picture loading progress
        } else if(data instanceof Animation){
            /* Load animation */
        } else if(data instanceof Video){
            /* Load video */
        } else if(data instanceof Sound){
            /* Load sound */
        }else {
        }
    }
};

所以在这段代码中,所有的资源都被加载了,但是我想显示加载的进度。知道我错过了什么吗?

你在加载器中"忙循环",所以浏览器没有机会重新绘制/更新画布。

你可以实现一个setTimeout(getNext, 0)或者把draw函数放在一个requestAnimationFrame循环之外轮询当前状态。在这种情况下,我建议使用前者。

在伪代码中,这是让它工作的一种方法:

//Global:
    currentItem = 0
    total = numberOfItems
//The loop:
    function getNextItem() {
        getItem(currentItem++);
        drawProgressToCanvas();
        if (currentItem < total)
            setTimeout(getNextItem(), 0);
        else
            isReady();
    }
    getNextItem(); //start the loader

根据需要采用

值为0的setTimeout将提示下一次有时间的呼叫(即。重绘后,清空事件堆栈等)。这里的isReady()只是加载所有内容后进入下一步的一种方法。(如果您发现使用0有任何问题,请尝试使用例如16。)

使用requestAnimationFrame是一种更低级、更有效的方法。目前并不是所有的浏览器都支持它,但是有一些多填充可以帮你解决这个问题——对于这种用法,它不是那么重要,但只是让你知道这个选项(如果你还没有)。