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