简体   繁体   中英

HTML5 canvas progress bar

I want to draw a progress bar on HTML5 canvas while assets are loading, and I use this code:

Assets.Download(function(_loaded) {
    console.log("callback called");//its displayed in log
    ctx.beginPath();
    ctx.rect(0, 0, _loaded * 500, 50);
    ctx.fillStyle = "#8ED6FF";
    ctx.fill();
    ctx.lineWidth = 5;
    ctx.strokeStyle = "black";
    ctx.stroke();
    sleep(1000);
})

function(_loaded) is called from Download() , and it works (I mean it's displaying in the log "callback called" , but the canvas is updated after the whole Download() ends. So all time I see nothing... and then the full bar :(

Can anyone help me?

in javascript you can not listen for filedownload progress, the only thing you can listen for is file download completion

so if you have a list of N images when each finishes you could call the update progress bar but you cant do it for each byte that is downloaded

You actually can monitor download with the XMLHttpRequest Level 2 progress event. XHR2 is supported in most of the browsers that has a canvas with IE9 being an exception.

var xhr = new XMLHttpRequest();


xhr.addEventListener('progress', function(event) {

    console.log(event.loaded / event.total);
},
false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM