如果使用dom图像元素,为什么画布drawImage不起作用?

时间:2013-09-07 16:31:13

标签: javascript dom canvas

我写了一个canvas js程序,但是如果我在ubuntu 13.04 chromium中使用DOM元素它不起作用(它在firefox 23.0中很好)。这是代码:

<body>
<canvas id="map" width="600" height="600"></canvas>
<img id="photo" src="jiuwo.jpg" style="display:none;">
<img id="frame" src="frame.png" style="display:none;">
</body>
<script type="text/javascript">
function drawGallary(){
    var canvas = document.getElementById('map');
    if(canvas.getContext){
        var ctx = canvas.getContext('2d');
        var img1 = document.getElementById('photo');
        var img2 = document.getElementById('frame');
        ctx.drawImage(img1, 300, 300, 100, 100, 20, 21, 100, 100); // block of image
        ctx.drawImage(img2, 0, 0);
    }
}
</script>

我发现如果我把drawImage放到onload函数中,它运行良好:

function drawGallary2(){
    var canvas = document.getElementById('map');
    if(canvas.getContext){
        var ctx = canvas.getContext('2d');
        var img1 = new Image();
        img1.src = "jiuwo.jpg";
        img1.onload = function(){
            ctx.drawImage(img1, 300, 300, 100, 100, 20, 21, 100, 100);
        }
        var img2 = document.getElementById('frame');
        img2.onload = function(){
            ctx.drawImage(img2, 0, 0);
        }
    }
}

如果使用DOM元素作为图像源,是否需要onload?感谢。

1 个答案:

答案 0 :(得分:2)

确保您使用window.onload为页面充分加载时间。

通过这种方式,您的图像可以在画布上完全绘制。

// wait until the page is fully loaded

window.onload = function() {

    function drawGallary(){
        var canvas = document.getElementById('map');
        if(canvas.getContext){
            var ctx = canvas.getContext('2d');
            var img1 = document.getElementById('photo');
            var img2 = document.getElementById('frame');
            ctx.drawImage(img1, 300, 300, 100, 100, 20, 21, 100, 100); 
            ctx.drawImage(img2, 0, 0);
        }
    }

} // end window.onload