在代码中调用对象的功能不起作用

时间:2018-03-07 10:40:13

标签: javascript

我一直在使用Sprites做一个简单的画布动画,一切都很好,只要我从浏览器控制台调用对象函数,在代码中运行coin.draw()并且它可以工作,但它不会显示附加到此的图像对象,当我在浏览器控制台中键入coin.draw()时,它通常会绘制图像,你能解释一下吗?

<!DOCTYPE html>
<html>

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

<body>
    <canvas id="myCanvas"></canvas>
    <script type="text/javascript">
    coins = new Image();
    coins.src = "coins.png";

    var canvas = document.getElementById('myCanvas');
    canvas.height = 500;
    canvas.width = 500;
    var ctx = canvas.getContext('2d');

    function Sprite(option) {

        var that = {};

        that.img = option;
        that.width = 44;
        that.height = 40;
        that.context = ctx;
        that.frameIndex = 0;
        that.fps = 60;
        that.time = 0;
        that.start = true;

        that.draw = function() {

            that.context.drawImage(
                that.img,
                0 + that.width * that.frameIndex,
                0,
                that.width,
                that.height,
                0,
                0,
                that.width,
                that.height);

            console.log("works");
        }

        that.update = function() {

            that.time++

                if (that.time > that.fps) {

                    that.time = 0;
                    //that.context.clearRect(0, 0, canvas.width, canvas.height);
                    that.draw();
                    that.frameIndex++;

                    if (that.frameIndex == (coins.width / that.width) - 1) {

                        that.frameIndex = 0;

                    }

                }
        }

        that.animate = function() {

            that.update()
            console.log(that.time);
            window.requestAnimationFrame(that.animate());

        }

        return that;
    }


    var coin = new Sprite(coins);
    coin.draw();
    </script>
</body>

</html>

1 个答案:

答案 0 :(得分:0)

我认为您遇到的问题是因为第一次运行脚本时图像没有被加载。您可以做的是使Sprite()函数检查并且仅在加载图像后执行。

改变这一位......

var coin = new Sprite (coins);
coin.draw();

到此......

var coin = new Sprite (coins);

// coins may not be loaded - we need to check here before we use it
if (coins.complete) {
    coin.draw();
}
else {
    coins.addEventListener("load", function() {
        coin.draw();
    });
}

检查图像是否已经加载(如果它已被缓存,它将会被加载)并执行draw()。如果不是它将事件处理程序附加到load事件,那么一旦加载图像,它将执行draw()

这不包括加载错误的可能性。如果需要,您可以为其添加单独的事件处理程序。