context.drawImage behaving weirdly

后端 未结 1 1271
耶瑟儿~
耶瑟儿~ 2021-01-21 21:10

I have:



And then:



        
1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-21 21:44

    That is because loading images is an asynchronous operation. The alert call helps the browser to wait a bit so the image loading can finish. Therefor the image will be available at drawImage that follows.

    The correct way to implement this is to use the code this way:

    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');
    var image = new Image(); //document.createElement('img'); for Chrome due to issue
    
    // add a onload handler that gets called when image is ready
    image.onload = function () {
        context.drawImage(this, 0, 0, 300, 400);
    }
    
    // set source last so onload gets properly initialized
    image.src = 'http://4.bp.blogspot.com/...-21+Kingfisher.JPG';
    

    The draw operation inside the callback for onload could just as easily have been a function call:

    image.onload = nextStep;
    // ...
    
    function nextStep() {
        /// draw image and other things...
    }
    

    0 讨论(0)
提交回复
热议问题