javascript - 我需要帮助查找 JavaScript 迷你游戏中的错误(我没有收到三个错误)

标签 javascript html google-chrome

这是我第一次从头开始制作迷你游戏。

Google Chrome 在运行时给我这些错误:

Uncaught TypeError: Cannot call method 'draw' of undefined  Logic.js:28
loop                                                        Logic.js:28
startLoop                                                   Logic.js:35
init                                                        Logic.js:19

当我使用“setInterval”时它工作正常,但我想要最新的东西。 我不认为 requestAnimationFrame 与它有任何关系。

但我不明白有什么问题!请帮忙。

// Create the canvas
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
canvas.addEventListener('click', canvasClick, false);

//Declarations
var isPlaying = false;
var animeFrame = window.requestAnimationFrame ||
                 window.webkitRequestAnimationFrame ||
                 window.mozRequestAnimationFrame ||
                 window.msRequestAnimationFrame ||
                 window.oRequestAnimationFrame;

var Pair1;
var Pair2;

//init
function init(){
    startLoop();
    Pair1 = new Pair();
    Pair2 = new Pair();
    alert('init called');
}

//Draw
function loop(){
    if(isPlaying){
        Pair1.draw();
        Pair2.draw();
        animeFrame(loop);
    }
}
function startLoop(){
    isPlaying = true;
    loop();
}

function stopLoop(){
    isPlaying = false;
}

//Interface
function canvasClick(){
    var X = event.x;
    var Y = event.y;

    X -= canvas.offsetLeft;
    Y -= canvas.offsetTop;

    if(X > Pair1.X && X < Pair1.X + 64){
        if(Y > Pair1.Y && Y < Pair1.Y + 96){
            alert('Clicked Pair1');
        };
    };
}

//Create Images
var pairImg = new Image();
pairImg.src = "images/Gold_Pair.png";
pairImg.addEventListener('load',init,false)

//Pair
function Pair(){
    var X = Math.floor(Math.random() * (canvas.width - 64));
    var Y = Math.floor(Math.random() * (canvas.height - 96));
}

//Draw
Pair.prototype.draw = function(){
    ctx.drawImage(pairImg, this.X, this.Y, 64, 96);
};

感谢您的回复!!!

最佳答案

您的“init”函数调用“startLoop”,它调用“loop”,它期望“Pair1”和“Pair2”已初始化。但是,“init”直到调用“startLoop”之后才会初始化它们。

尝试更改“init”:

function init(){
    Pair1 = new Pair();
    Pair2 = new Pair();
    startLoop();
    alert('init called');
}

关于javascript - 我需要帮助查找 JavaScript 迷你游戏中的错误(我没有收到三个错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11935709/

相关文章:

javascript - 将 session 传递给 Body onLoad 并接收到另一个页面

javascript - 自动下载行为和后退按钮问题

html - 如何延迟我的 animate.css 效果?

javascript - 在 Javascript 中通过标签名称获取信息

html - 更改 HTML 密码字段中显示的符号

javascript - Jquery动画循环

javascript - 正则表达式帮助计算字符串中的括号值

javascript - 尝试权限请求通知错误 Javascript

javascript - 在帧中设置 location.hash

css - 谷歌浏览器边框半径问题