Cancel single image request in html5 browsers

后端 未结 4 2069
臣服心动
臣服心动 2020-11-30 06:06

I\'m loading (large) images dynamically to draw into a html5 canvas, something like this:

var t = new Image();
t.onload = ...
t.src = \'http://myurl\';
         


        
4条回答
  •  孤城傲影
    2020-11-30 06:19

    This is the only way that I managed to get it to work in all modern browsers (Chrome, Safari, Mobile-Safari, Firefox, and IE9).

    • Load an empty and hidden iframe
    • append an image tag to the body in the iframe
    • when the img.onload completes, you can use that image dom element to draw to an html5 canvas with drawImage()
    • if you want to cancel the load, issue a stop() on the iframe's contentWindow (or execCommand("stop", false) on contentDocument in IE).
    • after you cancel a image load, you can reuse the iframe to load more images.

    I created a class for this, and put the coffeescript code (and it's compiled javascript) on github: Cancelable Html5 Image Loader

    If you want to play with it, I also created a jsfiddle to test it out. Remember to start Fiddler2 (or something like it) to see that the actual network request is really being canceled.

提交回复
热议问题