我正在尝试在画布上绘制一个白色块,但显示错误

时间:2014-03-08 12:34:16

标签: javascript

我正在尝试在画布上绘制白色块,但显示错误: 未捕获的TypeError:无法在'CanvasRenderingContext2D上执行'putImageData'未找到与提供的签名匹配的函数

代码:

function wall(x, y, height, width) {
// Свойство
this.x = x;
this.y = y;
this.height = height;
this.width = width;
this.img = new Image();

// Метод
this.createImg = function(ctx) {

    ctx.fillStyle = "white";
    ctx.rect(this.x, this.y, this.height, this.width);
    ctx.fill();
    //img = ctx.getImageData(0, 0, this.height, this.width);
}

this.getImg = function() {
    return this.img;
}
}

define(function() {
var humanX = 0;

var humanY = 0;
var canvas;
var ctx;

var prevBackground = new Image();
var human = new Image();
var prevHumanX = 0;
var prevHumanY = 0;
var wallObj;

function StartGame() {
    canvas = document.getElementById("myCanvas");
    if (canvas.getContext) {
        ctx = canvas.getContext("2d");

        ctx.fillStyle = "black";
        ctx.rect(0, 0, 810, 600);
        ctx.fill();

        prevBackground = ctx.getImageData(0, 0, 810, 600);

        wallObj = new wall(100, 100, 50, 50);
        wallObj.createImg(ctx);

        makeHuman();

    }
    gameLoop = setInterval(doGameLoop, 16);
    window.addEventListener('keydown', whatKey, true);
}

function makeHuman() {
    ctx.beginPath();
    ctx.arc(15, 15, 15, 0, 2*Math.PI, true);
    ctx.closePath();
    ctx.fillStyle = "rgb(222, 103, 0)";
    ctx.fill();

    human = ctx.getImageData(0, 0, 30, 30);
    ctx.putImageData(prevBackground, 0, 0);
}

function doGameLoop() {
    ctx.putImageData(prevBackground, 0, 0);
    ctx.putImageData(human, humanX, humanY);

    ctx.putImageData(wallObj.getImg(), humanX, humanY);

    //console.log(wallObj.getImg());

    //ctx.putImageData(human, 0, 0);
}

function whatKey(evt) {
    var flag = 0;

    prevHumanX = humanX;
    prevHumanY = humanY;

    switch (evt.keyCode) {
        case 37:
            humanX = humanX - 5;
            if (humanX < 0) {
                humanX = 0;
                flag = 1;
            }
            break;

        case 39:
            humanX = humanX + 5;
            if (humanX > 770) {
                humanX = 770;
                flag = 1;
            }
            break;

        case 40:
            humanY = humanY + 5;
            if (humanY > 570) {
                humanY = 570;
                flag = 1;
            }
            break;

        case 38:
            humanY = humanY - 5;
            if (humanY < 0) {
                humanY = 0;
                flag = 1;
            }
            break;
    }

    if (flag) {
        humanX = prevHumanX;
        humanY = prevHumanY;

    }
}

return StartGame;
});

0 个答案:

没有答案