画布有问题

时间:2016-01-30 02:30:28

标签: javascript html image canvas cat

你能帮帮我吗?猫的图像没有显示在画布上。我不知道我的代码有什么不对。

HTML:

<html>
<head>
    <link type="text/stylesheet" rel="stylesheet" href="style.css" />

</head>
<body>
    <center>
        <h1>Little Cat</h1>
        <canvas id="main" height="300" width="300"></canvas>
    </center>
    <script type="text/javascript" rel="javascript" src="script.js">Try another browser</script>
</body>
</html>

使用Javascript:

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


var catI = new Image();
    catI.src = "Image/cat.gif";



function Cat(x, y){
    this.x = x || 20, this.y = y || 50, this.img = catI, this.speed = 3,     this.keyInput = {};

this.display = function(){

    //control movements
    if(this.keyInput[38] === true){
        this.y -= this.speed;
    }
    if(this.keyInput[40] === true){
        this.y += this.speed;
    }
    if(this.keyInput[37] === true){
        this.x -= this.speed;
    }
    if(this.keyInput[39] === true){
        this.x += this.speed;
    }
    else{
        this.x += 0;
        this.y += 0;
    }

    //stay within the canvas
    if(this.x < 0){
        this.x = 0;
    }
    if(this.x >  canvas.width - 50){
        this.x = canvas.width - 50;
    }
    if(this.y < 0){
        this.y = 0;
    }
    if(this.y >  canvas.height - 50){
        this.y = canvas.height - 50;
    }

    ctx.drawImage(catI, this.x, this.y);
};

}

var cat = new Cat(50, 50);

document.addEventListener("keydown", function(e){
    cat.keyInput[e.keyCode] = true;
});

document.addEventListener("keyup", function(e){
    cat.keyInput[e.keyCode] = false;
});

function animate(){
    cat.display();
}


window.requestAnimationFrame(animate);

1 个答案:

答案 0 :(得分:0)

我建议你使用JSLint。所以你可以找到问题所在。 链接:JSLint.com

试图发现你的代码有什么不好但不能。工作了一分钟,但我丢失了代码。

对不起,祝你好运,如果我修好它就会编辑这个:)