我正在使用JavaScript和HTML5制作二维棒球游戏,并且尝试移动使用JavaScript绘制的图像,如下所示:

//canvas
var c = document.getElementById("gameCanvas");
var ctx = c.getContext("2d");
//baseball
var baseball = new Image();
baseball.onload = function() {
    ctx.drawImage(baseball, 400, 425);
};
baseball.src = "baseball2.png";


我不确定如何移动它,我已经看到很多人似乎只键入ballXballY之类的东西,但我不明白实际的xy定义是从哪里来的。到目前为止,这是我的代码:

http://jsfiddle.net/xRfua/

预先感谢您的任何帮助!

最佳答案

将球的位置存储在几个变量中,然后可以在绘制对象之前根据这些值进行翻译,类似这样的方法应该起作用:

var baseballX = 0;
var baseballY = 0;
var goLeft = 0;
var goRight = 0;
var goUp = 0;
var goDown = 0;
var ballSpeed = 5;

function renderCanvas() {
   // clear the canvas
   ctx.clearRect(0, 0, c.width, c.height);
   ctx.save();

   if(goLeft) baseballX -= ballSpeed;
   if(goRight) baseballX += ballSpeed;
   if(goUp) baseballY -= ballSpeed;
   if(goDown) baseballY += ballSpeed;

   // translate to balls position
   ctx.translate(baseballX, baseballY);
   // draw the image
   ctx.drawImage(baseball, 0, 0);
   ctx.restore();
}

// handle any user input
window.addEventListener('keyup', function(event) {
   switch (event.keyCode) {
     case 37: // Left
       goLeft=0;
     break;
     case 38: // Up
       goUp=0;
     break;
     case 39: // Right
       goRight=0;
     break;
     case 40: // Down
       goDown=0;
     break;
   }
 }, false);

window.addEventListener('keydown', function(event) {
   switch (event.keyCode) {
     case 37: // Left
       goLeft=1;
     break;
     case 38: // Up
       goUp=1;
     break;
     case 39: // Right
       goRight=1;
     break;
     case 40: // Down
       goDown=1;
     break;
   }
 }, false);

// set off timer
setInterval(renderCanvas,1000/100);


这是一个工作示例:fiddle

09-25 18:17