0

我正在慢慢学习一些基本的 HTML 5 和 Javascript。我编写了一个 Javascript 文件,该文件假设显示图像,然后通过按右键更改图像的位置。图像加载,但当我按右时它不会改变位置。我究竟做错了什么?

var canvas = document.createElement("canvas");
canvas.width = 800;
canvas.height = 600;
canvas.style  = "border:2px solid blue";
canvas.addEventListener('keydown', doKeyDown, true);
var ctx = canvas.getContext("2d");
document.body.appendChild( canvas );

var guy1Image = new Image();
guy1Image.onload = function () {
   ctx.drawImage( guy1Image, x, y );
};
guy1Image.src = "img/1.png";
var x = 0;
var y = 0;

function doKeyDown( e ) {
  if ( e.keyCode == 39 ) {
 x = 128;
     y = 128;
  }
}
4

2 回答 2

1

按下键清除画布并重新绘制它:)

   function doKeyDown( e ) {
      if ( e.keyCode == 39 ) {
         var canvas=document.getElementsByTagName("canvas");
         var ctx = canvas.getContext("2d");
         ctx.clearRect( 0, 0, 800, 600 );
         x = 128;
         y = 128;
         ctx.drawImage( guy1Image, x, y );
      }
   }
于 2013-09-16T04:50:10.963 回答
1

您不能专注于画布元素,这意味着您的 keydown 事件将不起作用。这里有一些解决方法

var lastDownTarget;
window.onload = function() {
    document.addEventListener('mousedown', function(event) {
        lastDownTarget = event.target;
        alert('mousedown');
    }, false);

    document.addEventListener('keydown', function(event) {console.log(lastDownTarget)
        if(lastDownTarget == canvas) {
            alert('keydown');
        }
    }, false);
}
于 2013-09-16T05:02:48.873 回答