Canvas中 drawImage繪制圖片不顯示


在學習 html5中的 Canvas.drawImage時寫了如下代碼:

<!doctype html>
<html>
    <head><title>研究</title></head>
    <body>
        <canvas id="canvas" style="width:500px;height:400px; border:1px solid red"></canvas>
        <img id="img" src="ggg.jpg"  hidden />
    </body>
    <Script type="text/javascript">
        var cxt = document.getElementById("canvas").getContext("2d");
        var imgElement = document.getElementById("img");
       cxt.drawImage(imgElement, 10, 10, 200, 200);
    </Script>
</html>

在charome和firefox中都無法顯示繪制的圖片效果。后來查詢了很多資料,才知道canvas在繪制圖片的時候要等到img的圖片完全加載到客戶端后才可以繪制正確,現在的代碼中直接是繪制圖片,圖片還沒加載完就開始在繪制圖片了,把代碼稍微改下:

  

<!doctype html>
<html>
    <head><title>研究</title></head>
    <body>
        <canvas id="canvas" style="width:500px;height:400px; border:1px solid red"></canvas>
        <img id="img" src="ggg.jpg"  hidden />
    </body>
    <Script type="text/javascript">
        var cxt = document.getElementById("canvas").getContext("2d");
        var imgElement = document.getElementById("img");
       setTimeout(function () { cxt.drawImage(imgElement, 10, 10, 200, 200); },0);
    </Script>
</html>

  或者

<!doctype html>
<html>
    <head><title>研究</title></head>
    <body>
        <canvas id="canvas" style="width:500px;height:400px; border:1px solid red"></canvas>
        <img id="img" src="ggg.jpg"  hidden />
    </body>
    <Script type="text/javascript">
        var cxt = document.getElementById("canvas").getContext("2d");
        var imgElement = document.getElementById("img");
        imgElement.onload = function () { cxt.drawImage(imgElement, 10, 10, 200, 200); };
    </Script>
</html>

  就可以正常顯示繪制的圖片了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM