变量没有定义JS

时间:2014-10-23 23:30:51

标签: javascript html google-chrome variables var

嗨,我对编程很陌生,这可能是一个非常容易回答的问题,但我不知道如何修复它。我正在制作一种用箭头键绘制的艺术程序,我也使用了崇高的文本2作为我的编辑。

根据开发。控制台没有定义,但它看起来像我定义。无论如何,我寻找答案,但我看到的大多数事情只是忘记定义变量的人,否则它不是JS,HTML。

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var keysDown = {};
window.addEventListener('keydown', function(e) {
    keysDown[e.keyCode] = true;
});
window.addEventListener('keyup', function(e) {
    delete keysDown[e.keyCode];
});

function update(mod) {
    if (37 in keysDown) {
        mySprite.x -= mySprite.speed * mod;
    }
    if (38 in keysDown) {
        mySprite.y -= mySprite.speed * mod;
    }
    if (39 in keysDown) {
        mySprite.x += mySprite.speed * mod;
    }
    if (40 in keysDown) {
        mySprite.y += mySprite.speed * mod;
    }
}

function render() {
var img = document.getElementById("super");
ctx.drawImage(img,mySprite.x,mySprite.y);
}
function run() {
    update((Date.now() - time) / 1000);
    render();
    time = Date.now();
}

var time = Date.now();
setInterval(run, 10);
<html>
    <head>
        <title>Draw With PNGS</title>
    </head>
    <body>
        <canvas id="canvas" height="400" width="800" ></canvas>
        <img id="super" src="superman.png" alt="superman" width="20" height="20">
        <script type="text/javascript" src="main.js"></script>
            </body>
</html>

1 个答案:

答案 0 :(得分:0)

我在在线小提琴引擎上尝试了这个,缺少的是你的mySprite声明。

您需要像keysDown对象一样全局声明精灵。所以我将精灵设置为var mySprite ={speed:10, y:0, x:0};

您需要初始化x和y以及速度,否则您将尝试使用未定义的值进行数学运算,这也将x和y设置为NaN(不是数字)。

This is the link to the JS fiddle.

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var mySprite ={speed:10, y:0, x:0};
var keysDown = {};
window.addEventListener('keydown', function(e) {
    keysDown[e.keyCode] = true;
});
window.addEventListener('keyup', function(e) {
    delete keysDown[e.keyCode];
});
 
function update(mod) {
    if (37 in keysDown) {
        mySprite.x -= mySprite.speed * mod;
    }
    if (38 in keysDown) {
        mySprite.y -= mySprite.speed * mod;
    }
    if (39 in keysDown) {
        mySprite.x += mySprite.speed * mod;
    }
    if (40 in keysDown) {
        mySprite.y += mySprite.speed * mod;
    }
}
 
function render() {
var img = document.getElementById("super");
ctx.drawImage(img,mySprite.x,mySprite.y);
}

function run() {
    update((Date.now() - time) / 1000);
    render();
    time = Date.now();
}
 
var time = Date.now();
setInterval(run, 10);
<html>
    <head>
        <title>Draw With PNGS</title>
    </head>
    <body>
        <canvas id="canvas" height="400" width="800" ></canvas>
        <img id="super" src="superman.png" alt="superman" width="20" height="20">
        <script type="text/javascript" src="main.js"></script>
            </body>
</html>