javascript - 使用ctx.drawImage在对象数组中显示图像

时间:2016-02-06 10:57:17

标签: javascript jquery html arrays html5

它没有显示图像,我尝试了所有可能的方法,我无法弄清楚如何。我该怎么做:

1)如何创建新的对象对象('20','X',250,100,'img');并指定我想要使用哪张图片? img.player或img.player.src还是只是img? 2)如何遍历objectArray在画布中全部显示它们?

15index.html: 38 Uncaught TypeError: Failed to execute 'drawImage'
on 'CanvasRenderingContext2D': The provided value is not of type '(HTMLImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap)'

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

<head>
  <title></title>
</head>

<body>

  <canvas id="ctx" width="500" height="500" style="border:1px solid #000000;"></canvas>

  <script>
    var WIDTH = 500;
    var HEIGHT = 500;
    var ctx = document.getElementById("ctx").getContext("2d");
    ctx.font = '30px Arial';

    var img = {};

    img.player = new Image();
    img.player.src = "FireMonster.png"

    var objectArray = {};

    function object(id, name, x, y, img) {

      var object3 = {
        x: x,
        y: y,
        name: name,
        id: id,
        img: img,

      };

      objectArray[id] = object3;
    }

    object('20', 'X', 250, 100, 'img');
    object('21', 'P', 150, 150, 'img');

    drawingObject = function(something) {

      ctx.drawImage(something.img, something.x, something.y);

    }

    update = function() {

      for (var x in objectArray) {

        drawingObject(objectArray[x]);

      }
    }


    setInterval(update, 40);
  </script>
</body>

</html>

1 个答案:

答案 0 :(得分:1)

您正在将'img'的文字传递给object function而不是Image个对象。试试这个:

object('20', 'X', 250, 100, img.player);
object('21', 'P', 150, 150, img.player);