0
我試圖用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/
Yeah..the效果我想創建是一次矩形一路向右移動需要一路向下移動,然後同時向左,然後再起來...... –
明白了!謝謝! –