2016-10-04 12 views
0

私は、キャンバスと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/

答えて

0

あなたは自分の矩形のYの値を変更する必要はなく、animateUp機能で、この行を変更するX.

ボックスは、あなたの中で下に移動作ら私が作成したいjsFiddle

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

Yeah..the効果は長方形が右にすべての道を移動したら、ダウンすべての方法を移動する必要があると左に同じ、その後、バックアップしています... –

+0

ありがとうございました! –

関連する問題