2013-12-21 86 views
0

我現在面臨一個問題,鼠標事件似乎不起作用。我有一個按鈕,精靈和玩家精靈,我想,當我按一下按鈕,玩家要移動butit沒有,那麼這裏的mycode的:HTML5/CANVAS:鼠標事件問題

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 
    }; 
} 

回答

0

你在做什麼是喜歡你點擊時, doMouseDown函數調用並結束。
,你需要調用這個函數多次獲得animation.so,
你可以嘗試像
如果點擊var clicked=true

,並把這個下面的代碼在循環
if (clicked){
x+=4
}

+0

好吧,我要去試試這個。謝謝 – user2962195