JS函数调用不起作用

时间:2016-07-01 20:35:20

标签: javascript html canvas

我尝试编写一个简单的JS画布,但它不会画画。如果我在chrome控制台中调用renderCanvas(),它可以正常工作,但如果我在代码中调用它,则不行。有什么想法吗?我确定图片在那里......

<!DOCTYPE html>
<html>
<head>
    <title>JSolitaire</title>
</head>
<body>
    <canvas id="canvas" width="640" height="480"></canvas>
    <script>
    renderCanvas(); 
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");  
    var bgReady = false;
    var bgImage = new Image();
    bgImage.src = "background.png";
    bgImage.onload = new function(){
        bgReady = true;
    };  

    function renderCanvas(){
        if(bgReady)
            ctx.drawImage(0, 0, bgImage);
    };
    </script>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

没有必要使用bgReady你可以这样做

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");  
var bgImage = new Image();
bgImage.src = "background.png";
bgImage.onload = function() {
    renderCanvas(); 
};  
function renderCanvas() {
    ctx.drawImage(bgImage, 0, 0);
};