빨간색 사각형이 루프에서 약간 앞뒤로 움직이는 유휴 애니메이션을 만들려고합니다. 어떤 이유로 든 반대 방향으로 이동하는 대신 지정된 임계 값에 도달하면 중지됩니다.
내가 뭘 잘못 했어?
<canvas id="myCanvas" width="1500" height="500" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// Spaceship structure
var shipWidth = 250;
var shipHeight = 100;
// Canvas parameters
var cWidth = canvas.width;
var cHeight = canvas.height;
// Positioning variables
var centerWidthPosition = (cWidth / 2) - (shipWidth / 2);
var centerHeightPosition = (cHeight / 2) - (shipHeight / 2);
var requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
function drawShip(){
ctx.clearRect(0, 0, cWidth, cHeight);
ctx.fillStyle = "#FF0000";
ctx.fillRect(centerWidthPosition,centerHeightPosition,shipWidth,shipHeight);
centerWidthPosition--;
if (centerWidthPosition < 400){
++centerWidthPosition;
}
requestAnimationFrame(drawShip);
}
drawShip();
</script>
@TheAmberlamps가 그 이유를 설명했습니다. 여기서 저는 당신이하려는 일을 성취 할 수있는 해결책을 제공합니다.
크기를 변경하는 속도 변수를 사용하십시오. X 위치는 항상 속도 값만큼 증가합니다. 속도는 화면 가장자리에서 방향을 변경합니다.
// use a velocity variable
var xspeed = 1;
// always increase by velocity
centerWidthPosition += xspeed;
// screen edges are 0 and 400 in this example
if (centerWidthPosition > 400 || centerWidthPosition < 0){
xspeed *= -1; // change velocity direction
}
개체가 앞뒤로 튀는 경우에 다른 조건을 추가했습니다. || 이후 선택을 제거하십시오. 그렇게하고 싶지 않다면.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다