HTML5 / CANVAS:鼠标事件问题

时间:2013-12-21 19:11:38

标签: javascript html5 events canvas mouse

我现在面临一个问题,鼠标事件似乎不起作用。我有一个按钮精灵和一个玩家精灵,我希望当我点击按钮时,玩家应该移动但是没有,这里是我的代码:

var canvas = document.getElementById("canvas_1");
ctx = canvas.getContext("2d");
canvas.addEventListener('mousedown', doMouseDown, true);
var X = 100;
var Y = 0;
var x = 0;
var y = 0;
var player = new Image();
var butt = new Image();
player.src = 'images/player.png';
butt.src = 'images/right.png';
player.onload = function () {
    ctx.drawImage(player, x, 0);
}
butt.onload = function () {
    ctx.drawImage(butt, X, Y);
}

update = function () {
    ctx.clearRect(0, 0);
    ctx.drawImage(player, x, y);
}
setInterval(update, 1000 / fps.getFPS());
var fps = {
    startTime: 0,
    frameNumber: 0,
    getFPS: function () {
        this.frameNumber++;
        var d = new Date().getTime(),
            currentTime = (d - this.startTime) / 1000,
            result = Math.floor((this.frameNumber / currentTime));

        if (currentTime > 1) {
            this.startTime = new Date().getTime();
            this.frameNumber = 0;
        }
        return result;

    }
};

function doMouseDown(event) {
    var mousePos = getMousePos(canvas, event);

    if ((mousePos.x >= X && mousePos.x <= X + butt.width) && (mousePos.y >= Y && mousePos.y <= Y + butt.height)) {
        x += 4;
    }
}

function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
        x: evt.clientX - rect.left,
        y: evt.clientY - rect.top
    };
}

1 个答案:

答案 0 :(得分:0)

您正在做的就像点击了doMouseDown函数调用并结束 你需要多次调用这个函数来获得动画。所以,
你可以尝试像  如果点击var clicked=true

并将此代码置于循环中 if (clicked){
x+=4
}