画布绘制图像不起作用

Canvas drawImage is Not Working

本文关键字:图像 不起作用 绘制 布绘制      更新时间:2023-09-26

此图片不会绘制到画布上。 它正在加载,我在 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>
img.onload = onImageLoad;

不是onImageLoad();,如果您包含括号,则正在执行函数