首頁  >  問答  >  主體

canvas - html5绘制图片的问题

为什么我把new Image()放在function里面时,图片出不来。
<!DOCTYPE html>
<html>

<head>
    <meta charset="{CHARSET}">
    <title></title>
</head>
<body onload="init()">
    <canvas id="girl"></canvas>
</body>
<script>
    var girl = document.getElementById("girl");
    var girlWidth = 800;
    var girlHeight = 400;
    girl.width = girlWidth;
    girl.height = girlHeight;
    var girlCans = girl.getContext('2d');
    
    
    function init(){
        drawGirl();
    }
    
    function drawGirl(){
        var girlPic = new Image();
        girlPic.src = "img/girl.jpg";
        girlCans.drawImage(girlPic,0,0, girlWidth, girlHeight);
    }
    
    
</script>

</html>

然而我把girlPic设为全局的就能正常显示
<!DOCTYPE html>
<html>

<head>
    <meta charset="{CHARSET}">
    <title></title>
</head>
<body onload="init()">
    <canvas id="girl"></canvas>
</body>
<script>
    var girl = document.getElementById("girl");
    var girlWidth = 800;
    var girlHeight = 400;
    girl.width = girlWidth;
    girl.height = girlHeight;
    var girlCans = girl.getContext('2d');
    var girlPic = new Image();
    girlPic.src = "img/girl.jpg";
    
    function init(){
        drawGirl();
    }
    
    function drawGirl(){
        
        girlCans.drawImage(girlPic,0,0, girlWidth, girlHeight);
    }
    
    
</script>

</html>

高洛峰高洛峰2765 天前366

全部回覆(2)我來回復

  • 怪我咯

    怪我咯2017-04-17 13:18:29

    因為在image設定完src後,需要一定的時間進行加載,在src設定完後馬上運行drawImage函數的時候,image實際上還什麼也沒有。
    比較適合的寫法是image.onload = girlCans.drawImage(girlPic,0,0, girlWidth, girlHeight);

    回覆
    0
  • 怪我咯

    怪我咯2017-04-17 13:18:29

    img加載是異步滴。需要用onload()

    回覆
    0
  • 取消回覆