drawImage() not working

女生的网名这么多〃 提交于 2019-11-30 05:56:55
markE

You almost have it...

You just have to give the image time to load before drawing it.

You give an image time to load with this code:

var logoImg = new Image();
logoImg.onload = function() {

    // At this point, the image is fully loaded
    // So do your thing!

};
logoImg.src = "myPic.png";

Here is complete code and a Fiddle: http://jsfiddle.net/m1erickson/GKK39/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>

<script>
    $(function(){

        var canvas=document.getElementById("canvas");
        var c=canvas.getContext("2d");

        function showIntro() {

            var phrase = "Click or tap screen to start";

            var logoImg=new Image();
            logoImg.onload=function(){

                c.clearRect (0, 0, canvas.width, canvas.height);

                var grd = c.createLinearGradient(0, 0, canvas.width, canvas.height);
                grd.addColorStop(0, "#9db7a0");
                grd.addColorStop(1, "#e6e6e6");
                c.fillStyle = grd;
                c.fillRect (0, 0, canvas.width, canvas.height);

                var originalWidth = logoImg.width;
                logoImg.width = Math.round((50 * document.body.clientWidth) / 100);
                logoImg.height = Math.round((logoImg.width * logoImg.height) / originalWidth);

                var logo = {
                  img: logoImg,
                  x: (canvas.width/2) - (logoImg.width/2),
                  y: (canvas.height/2) - (logoImg.height/2)
                }
                c.drawImage(logo.img, logo.x, logo.y, logo.img.width, logo.img.height);

                c.font = "bold 16px sans-serif";
                var mt = c.measureText(phrase);
                var xcoord = (canvas.width / 2 ) - (mt.width / 2);
                c.fillStyle = '#656565'
                c.fillText (phrase, xcoord, 30);

            }
            logoImg.src="http://dl.dropbox.com/u/139992952/car.png";

        }

        showIntro();       

    }); // end $(function(){});
</script>

</head>

<body>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!