canvas - html5绘制图片的问题
高洛峰
高洛峰 2017-04-17 13:16:29
0
2
367

为什么我把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>

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

membalas semua(2)
刘奇

因为在image设置完src后,需要一定的时间进行加载,在src设置完后马上运行drawImage函数的时候,image实际上还什么也没有。
比较合适的写法是image.onload = girlCans.drawImage(girlPic,0,0, girlWidth, girlHeight);

刘奇

img加载是异步滴。需要用onload()

Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!