简体   繁体   中英

Javascript - loading GIF freezed while drawing image to canvas (Phonegap/Cordova)

While i draw image to canvas, loading gif won't animate on phonegap/cordova, the code looks like this:

.hide{
display:none;
}
.absolute{
position:absolute;
}


<div id="loading" class="hide absolute">
<img src="loading.gif"/>
</div>

var drawCanvas = function (img) {

 var element = document.getElementById('loading')
     canvas = document.getElementById('canvas')
     context = canvas.getContext('2d');

     element.classList.remove('hide');

     setTimeout(function () {

      context.drawImage(img,0,0);
     }, 0);

     element.classList.add('hide');
};

I also tried replacing animated gif with css animation, but its exactly the same, the browser refuses to animate anything while drawing the canvas

Any help appreciated

NB: it happens not on desktop but only in cordova/phonegap, i guess the cause is lack of hardware performance on mobile (tested on Android tablet 4.1)

Try increasing the delay. A delay of 0 doesn't really help much as there is not enough time for some browser to do anything else. Give a frame or so. Also continue from inside the callback as it is asynchronous:

setTimeout(function () {
    context.drawImage(img,0,0);
    element.classList.add('hide');  // you'll probably like this to be here
}, 17);  // 17ms ~16.667ms as one frame takes @ 60 fps

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