0
基本上,當我按某個方向的某個箭頭鍵時,我的三角形正在移動,但在放開鍵後停止。我想加速,然後放開鍵,讓三角形以相同的速度加速無限的時間。這裏是我的相關代碼:HTML5帆布:如何保持形狀以恆定速度無限移動
var x = 0;
var y = 0;
var rotationDegrees = 0;
var movementRate = 5;
var rotationRate = 5;
function draw(){
context.fillStyle = "rgb(0, 0, 0)";
context.fillRect(0, 0, width, height);
drawTriangle(context, x, y, rectWidth, rectHeight, rotationDegrees);
if (rotationDegrees > 360){
rotationDegrees = 0;
}
window.requestAnimationFrame(draw);
}
window.requestAnimationFrame(draw);
window.addEventListener('keydown', function(event) {
console.log('this is where I describe the log: keydown event.which', event.which);
switch(event.which){
case 37:
console.log('left');
rotationDegrees = rotationDegrees - rotationRate;
break;
case 38:
console.log('up');
x = x + movementRate * Math.cos(rotationDegrees * Math.PI/180);
y = y + movementRate * Math.sin(rotationDegrees * Math.PI/180);
break;
case 39:
console.log('right');
rotationDegrees = rotationDegrees + rotationRate;
break;
case 40:
console.log('down');
x = x - movementRate * Math.cos(rotationDegrees * Math.PI/180);
y = y - movementRate * Math.sin(rotationDegrees * Math.PI/180);
break;
default:
}
});
function drawTriangle(context, x, y, rectWidth, rectHeight, rotationDegrees){
context.save();
var centerX = x + rectWidth/2;
var centerY = y + rectHeight/2;
context.translate(centerX, centerY);
var radians = rotationDegrees * (Math.PI/180);
context.rotate(radians);
context.strokeStyle = 'red';
context.beginPath();
var triangleOriginX = rectWidth/2;
var triangleOriginY = rectHeight/2;
context.moveTo(-triangleOriginX , -triangleOriginY);
context.lineTo(-triangleOriginX + rectWidth, -triangleOriginY + rectHeight/2);
context.lineTo(-triangleOriginX, -triangleOriginY + rectHeight);
context.closePath();
context.stroke();
context.restore();
這工作完美!非常感謝! –