HTML5 drawImage 使用问题

使用Image遇到的问题:

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8">
        <title></title>
        <script src="js/jquery-1.9.1.min.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript">
            $(function() {
                var jsCanv = document.getElementById("canv");
                var oCanv = jsCanv.getContext("2d");
                var img = new Image();
                img.src = "img.png";
                oCanv.drawImage(img, 220, 30); 
                
            })
        </script>
    </head>

    <body>
        <canvas id="canv" width="500" height="500">
            浏览器不支持
        </canvas>
    </body>

</html>

其实这种写法是有错误的,实际上只要一刷新图片就不显示出来。要想保证刷新正常显示需要在Image onload的时候重绘一次才行。测试在chrome 19下会出现的问题。

解决方案

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8">
        <title></title>
        <script src="js/jquery-1.9.1.min.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript">
            $(function() {
                var jsCanv = document.getElementById("canv");
                var oCanv = jsCanv.getContext("2d");
                var img = new Image();
                img.src = "img.png";
                img.onload = function() {
                    oCanv.drawImage(img, 220, 30); 
                }
            })
        </script>
    </head>

    <body>
        <canvas id="canv" width="500" height="500">
            浏览器不支持
        </canvas>
    </body>

</html>
posted @ 2014-11-27 09:33  孙悟饭  阅读(1931)  评论(0编辑  收藏  举报