Canvas翻译功能不会对键触发器起作用

时间:2014-04-19 18:25:49

标签: javascript html5 canvas javascript-events

当我把engine.map.ctx.translate(engine.moveX, engine.moveY);放得就像它完美无缺,但是当我尝试在按键触发时调用此函数时,它什么也没给我。

如果关键触发器有效,我正在检查警报,但是engine.map.ctx.translate(engine.moveX, engine.moveY);在switch语句中不起作用。

var engine = {}
    engine.moveX = 0;
    engine.moveY = 0;

engine.map = {}
    engine.map.canvas = document.getElementById('canvas');
    engine.map.ctx = engine.map.canvas.getContext('2d');

document.onkeydown = function(evt) {
    evt = evt || window.event;
    switch(evt.keyCode){
    case 37:
         engine.moveX -= 15;
         engine.map.ctx.translate(engine.moveX, engine.moveY);
         alert('left');
         break;
    case 38:
         engine.moveY -= 15;
         engine.map.ctx.translate(engine.moveX, engine.moveY);
         alert('up');
         break;
    case 39:
         engine.moveX += 15;
         engine.map.ctx.translate(engine.moveX, engine.moveY);
         alert('right');
         break;
    case 40:
         engine.moveY += 15;
         engine.map.ctx.translate(engine.moveX, engine.moveY);
         alert('down');
         break;
    }
};

1 个答案:

答案 0 :(得分:1)

ctx.translate命令不是为了重绘任何内容而设计的

它仅重新定位画布以用于后续绘制

所以你现在还需要重绘你的对象。