简体   繁体   English

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

[英]Why canvas drawImage doesn't work if using the dom image element?

I wrote a canvas js program, but it doesn't work if I use the DOM element in ubuntu 13.04 chromium(it is fine in firefox 23.0). 我写了一个canvas js程序,但是如果我在ubuntu 13.04 chromium中使用DOM元素它不起作用(它在firefox 23.0中很好)。 Here is the code: 这是代码:

<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>

I found that if I put the drawImage into onload function ,it works well: 我发现如果我把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);
        }
    }
}

is that onload needed if using the DOM element to be the image source? 如果使用DOM元素作为图像源,是否需要onload? Thanks. 谢谢。

Make sure you give time for the page to fully load using window.onload. 确保使用window.onload为页面提供完全加载的时间。

That way your images are fully available to draw on the canvas. 这样,您的图像就可以在画布上完全绘制。

// 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM