1

此图片不会绘制到画布上。它正在加载,我在 body.appendChild(img); 时看到它 叫做。有谁知道为什么它没有在画布上显示?我正在关注 udacity 的 html5 课程中的代码示例。感谢您的任何帮助!

<!DOCTYPE html>
    <html>
        <head>
            <title>First Game</title>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <link type="text/css" rel="stylesheet" href="TestCanvasCSS.css"/>
        </head>
        <body id="body">
            <script>
                var canvas;
                var ctx = null;
                var img = null;
                var body = null;

                setup = function() {
                    body = document.getElementById("body");
                    canvas = document.createElement("canvas");

                    ctx = canvas.getContext('2d');

                    //canvas.setAttribute("class","canvasMain");
                    canvas.width = window.innerWidth;
                    canvas.height = window.innerHeight;
                    body.appendChild(canvas);

                    img = new Image();
                    img.onload = onImageLoad();
                    img.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
                };

                onImageLoad = function() {
                    console.log("Image has loaded");
                    body.appendChild(img);
                    ctx.drawImage(img, 0, 0);
                };
                setup();
            </script>
            <!--  <script type="text/javascript" src="TestCanvas.js"> </script> -->
        </body>
    </html>
4

1 回答 1

3
img.onload = onImageLoad;

如果您包含括号,则不是onImageLoad();您正在执行该功能

于 2013-09-07T02:40:12.933 回答