在canvas中阻止默认操作,但在不使用canvas时恢复默认操作?

时间:2013-06-26 00:48:40

标签: events canvas keyboard

我的网站上有一个html5游戏,我阻止了AWSD keysSPACEBAR的操作。问题是游戏下的评论部分无法使用(更具体地说是AWSD keys or SPACEBAR);

有什么想法吗?

这是我的代码,它的漂亮菜鸟。忽略评论。

这是引用关键事件的函数:

function slide2() {
        drawSlide2();
        document.removeEventListener('click', mouseNext, false);
        document.addEventListener('click', mouseNext2, false);
        document.addEventListener('keydown', startCheckKeyDown2, false);
        document.addEventListener('keyup', startCheckKeyUp2, false);
        document.removeEventListener('keydown', startCheckKeyDown1, false);
        document.removeEventListener('keyup', startCheckKeyUp1, false);
}

awsd函数的事件监听器

function playGame() {
    drawBg(); 
    startLoop(); //we call this when the game loads
    updateHUD();
    document.addEventListener('keydown', checkKeyDown, false);
    document.addEventListener('keyup', checkKeyUp, false);
    notMoving = false;
}

这是我的keyCode函数

function checkKeyDown(e) { //e is a keyword or something we use to describe an event, whenever 
    var keyID = e.keyCode || e.which; //this is like an if statment except in one line // it gets the keyID from the differing ID's from different browsers. cross-browser 
    if (keyID === 38 || keyID === 87) {  //  **** Up arrow and W *****
        jet1.isUpKey = true;
        e.preventDefault(); //prevents default actions of the up and w key funcions, like scrolling up and down
    }
    if (keyID === 39 || keyID === 68) {  //  **** RIGHT & W *****
        jet1.isRightKey = true;
        e.preventDefault(); 
    }
    if (keyID === 40 || keyID === 83) {  //  **** DOWN or S *****
        jet1.isDownKey = true;
        e.preventDefault(); 
    }
    if (keyID === 37 || keyID === 65) {  //  **** LEFT or A *****
        jet1.isLeftKey = true;
        e.preventDefault(); 
    }
    if (keyID === 32) {  //  **** SPACEBAR *****
        jet1.isSpacebar = true;
        e.preventDefault(); 
    }
} 

function checkKeyUp(e) { 
    var keyID = e.keyCode || e.which; 
    if (keyID === 38 || keyID === 87) {  //  **** Up arrow and W *****
        jet1.isUpKey = false;
        e.preventDefault(); 
    }
    if (keyID === 39 || keyID === 68) {  //  **** RIGHT & W *****
        jet1.isRightKey = false;
        e.preventDefault(); 
    }
    if (keyID === 40 || keyID === 83) {  //  **** DOWN or S *****
        jet1.isDownKey = false;
        e.preventDefault(); 
    }
    if (keyID === 37 || keyID === 65) {  //  **** LEFT or A *****
        jet1.isLeftKey = false;
        e.preventDefault(); 
    }
    if (keyID === 32) {  //  **** SPACEBAR *****
        jet1.isSpacebar = false;
        e.preventDefault(); 
    }
}

1 个答案:

答案 0 :(得分:0)

快速回答是让画布处理它自己的关键事件:

  1. 启用canvas以获取keydown事件:yourCanvas.setAttribute(“tabindex”,0);
  2. 监听keydown事件:yourCanvas.addEventListener('keydown',handleKeydown,true);
  3. 在handleKeydown中,阻止事件冒泡:event.preventDefault();