使用JavaScript类属性的canvas drawImage错误

时间:2017-12-20 04:12:37

标签: javascript canvas

我正在尝试在drawImage函数上使用class。

但似乎drawImage函数无法获取变量monster的属性img。

我不知道会导致此错误的原因。

不太明白为什么浏览器会给我以下错误代码...请帮助我。

  

未捕获的TypeError:无法读取未定义的属性“img”。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Tower Defense</title>
    <style>
        canvas {
            padding: 0;
            margin: auto;
            display: block;
        }
    </style>
</head>

<body>
    <script>
        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext("2d");
        canvas.width = 500;
        canvas.height = 500;
        document.body.appendChild(canvas);

        function Monster(img, x = 0, y = 0, w,h) {
            this.img = img;
            this.x = x;
            this.y = y;
            this.w = w;
            this.h = h;
        }

        var monster;

        var DrawMonster = function(mons) {
            ctx.drawImage(mons.img, mons.x, mons.y, mons.w, mons.h);
        }

        var PreLoadImages = function() {
            var img = new Image();
            img.addEventListener("load", function() {     // or img.onload = function() { ...
                monster = new Monster(this, 0, 0, 100, 100);            
            });
            img.src = "res/Mons_Pirate.jpg";
        }

        PreLoadImages();
        DrawMonster(monster);

    </script>
</body>

</html>

请在测试时更改图像的链接(res / Mons_Pirate.jpg)。

1 个答案:

答案 0 :(得分:0)

DrawImage应该在图像加载函数内部.Monster的实例只在Image加载函数内部创建。图像将以异步加载。

   <!DOCTYPE html>
    <html lang="en">

     <head>
      <meta charset="UTF-8">
      <title>Tower Defense</title>
      <style>
        canvas {
            padding: 0;
            margin: auto;
            display: block;
        }
       </style>
     </head>

   <body>
       <script>
           var canvas = document.createElement("canvas");
           var ctx = canvas.getContext("2d");
           canvas.width = 500;
           canvas.height = 500;
           document.body.appendChild(canvas);

        function Monster(img, x = 0, y = 0, w,h) {
            this.img = img;
            this.x = x;
            this.y = y;
            this.w = w;
            this.h = h;
        }

        var monster;

        var DrawMonster = function(mons) {
            ctx.drawImage(mons.img, mons.x, mons.y, mons.w, mons.h);
        }

        var PreLoadImages = function() {
            var img = new Image();
            img.addEventListener("load", function() {     // or img.onload = 
            function() { 
                monster = new Monster(this, 0, 0, 100, 100);            
                DrawMonster(monster);
            });
            img.src = "res/Mons_Pirate.jpg";
        }

        PreLoadImages();

    </script>
</body>

</html>