创建一条没有鼠标或键盘事件的蛇

creating a snake with no mouse or keyboard events

我正在尝试使用 canvas 和 javascript 创建动画。我想重新创建一条在 canvas 边界运行的蛇,而不分配任何鼠标或键盘事件。目前我可以将我的矩形从左向右移动,但我想不出让它向下移动的方法。 有什么建议吗?这是我的代码:

function drawRectangle(myRectangle, context) {
context.beginPath();
context.rect(myRectangle.x, myRectangle.y, myRectangle.width,        myRectangle.height);
context.fillStyle = '#FB0202';
context.fill();

}

function animateUp(myRectangle, canvas, context, startTime) {
// update
var time = (new Date()).getTime() - startTime;

var linearSpeed = 100;
// pixels / second
var newX = linearSpeed * time / 1000;

if (newX < canvas.width - myRectangle.width / 2) {
    myRectangle.x = newX;
}

// clear
context.clearRect(0, 0, (canvas.width - 20), canvas.height);

drawRectangle(myRectangle, context);


// request new frame
requestAnimFrame(function() {
    animateUp(myRectangle, canvas, context, startTime);
});
}

  function animateDown(myRectangleDown, canvas, context, startTime) {
    // update
    var time = 0;

   var linearSpeed = 100;
   // pixels / second
   var newY = linearSpeed * time / 1000;

   if (newY < canvas.height - myRectangleDown.height / 2) {
       myRectangleDown.y = newY;
    }
     // clear
    context.clearRect(10, 0, (canvas.height - 20), canvas.width);

    drawRectangle(myRectangleDown, context);


     // request new frame
     requestAnimFrame(function() {
     animateDown(myRectangleDown, canvas, context, startTime);
   });
 }

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

var myRectangle = {
   x: 0,
   y: 0,
   width: 20,
   height: 20
};

var myRectangleDown = {
  x: 480,
  y: 0,
  width: 20,
  height: 20
 }

drawRectangle(myRectangle, context);

// wait one second before starting animation
 setTimeout(function() {
   var startTime = (new Date()).getTime();
   animateUp(myRectangle, canvas, context, startTime);
}, 1000);`

https://jsfiddle.net/zfy5atog/

您只需更改矩形的 Y 值,而不是 X。

更改 animateUp 函数中的这一行会使框在您的 jsFiddle 中向下移动

if (newX < canvas.width - myRectangle.width / 2) {
    myRectangle.y = newX; 
}