首页 > 其他 > 详细

Canvas中 drawImage绘制图片不显示

时间:2015-06-18 15:10:17      阅读:374      评论:0      收藏:0      [点我收藏+]

在学习 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>

  就可以正常显示绘制的图片了。

Canvas中 drawImage绘制图片不显示

原文:http://www.cnblogs.com/huaan011/p/4585735.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!