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

问题描述:

我试图用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/

你只需要改变你的矩形的Y值,而不是X.

更改在animateUp功能做成包装箱这条线在向下移动的的jsfiddle

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

Yeah..the效果我想创建是一次矩形一路向右移动需要一路向下移动,然后同时向左,然后再起来...... –

+0

明白了!谢谢! –