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

时间:2016-10-04 11:02:59

标签: javascript canvas requestanimationframe

我试图用canvas和javascript创建动画。我想重新创建一条在我的画布边框上运行的蛇,而不指定任何鼠标或键盘事件。目前我能够将我的矩形从左向右移动,但我无法想出让它向下移动的方法。 有什么建议吗?这是我的代码:

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/

1 个答案:

答案 0 :(得分:0)

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

更改animateUp函数中的这一行使你的框在jsFiddle

中向下移动
if (newX < canvas.width - myRectangle.width / 2) {
    myRectangle.y = newX; 
}