HTML5 Canvas: Get Event when drawing is finished

扶醉桌前 提交于 2020-01-19 05:37:59

问题


I'm drawing an image to a canvas element. I then have code that depends on this process to be finished. My code looks like this:

var myContext = myCanvasElement.getContext('2d'),
    myImg = new Image();

myImg.onload = function() {
    myContext.drawImage(containerImg, 0, 0, 300, 300);
};

myImg.src = "someImage.png";

So now, I would like to be notified when drawImage is done. I checked the spec but I couldn't find either an event or the possibility to pass a callback function. So far I just set a timeout, but this obviously is not very sustainable. How do you solve this problem?


回答1:


Like almost all Javascript functions, drawImage is synchronous, i.e. it'll only return once it has actually done what it's supposed to do.

That said, what it's supposed to do, like most other DOM calls, is queue-up lists of things to be repainted next time the browser gets into the event loop.

There's no event you can specifically register to tell you when that is, since by the time any such event handler could be called, the repaint would have already happened.




回答2:


Jef Claes explains it pretty well on his website:

Browsers load images asynchronously while scripts are already being interpreted and executed. If the image isn't fully loaded the canvas fails to render it.

Luckily this isn't hard to resolve. We just have to wait to start drawing until we receive a callback from the image, notifying loading has completed.

<script type="text/javascript">        
window.addEventListener("load", draw, true);

function draw(){                                    
    var img = new Image();
    img.src = "http://3.bp.blogspot.com/_0sKGHtXHSes/TPt5KD-xQDI/AAAAAAAAA0s/udx3iWAzUeo/s1600/aspnethomepageplusdevtools.PNG";                
    img.onload = function(){
        var canvas = document.getElementById('canvas');
        var context = canvas.getContext('2d');    

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




回答3:


You already have an event when the image loads, and you do one thing (draw). Why not do another and call the function that will do whatever it is you want done after drawImage? Literally just:

myImg.onload = function() {
    myContext.drawImage(containerImg, 0, 0, 300, 300);
    notify(); // guaranteed to be called after drawImage
};


来源:https://stackoverflow.com/questions/11207606/html5-canvas-get-event-when-drawing-is-finished

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!