简体   繁体   English

Javascript球无限地来回弹跳

[英]Javascript ball bouncing back and forth indefinitely

I'm writing a simple JS function that draws a ball in canvas and just bounces it back and forth between the left and right borders of the screen indefinitely. 我正在编写一个简单的JS函数,该函数在画布上绘制一个球,并无限期地在屏幕左右边界之间来回反弹。 I currently have it starting on the left side and going right. 我目前从左侧开始向右移动。 How I have it currently, it goes to the right but then gets stuck on the right edge; 我目前的状况如何,它会移到右侧,但会卡在右侧边缘; it doesn't bounce back. 它不会反弹。 Any tips? 有小费吗?

        var dx=4;
        var dy=4;
        var y=150;
        var x=10;
       function draw(){
          context= myCanvas.getContext('2d');
          context.clearRect(0,0,htmlCanvas.width,htmlCanvas.height);
          context.beginPath();
          context.fillStyle="#0000ff";
          context.arc(x,y,50,0,Math.PI*2,true);
          context.closePath();
          context.fill();
          if(x<htmlCanvas.width)
            x+=dx
          if(x>htmlCanvas.width)
            x-=dx;
        }
setInterval(draw,10); 

Change this: 更改此:

if(x<htmlCanvas.width)
    x+=dx
if(x>htmlCanvas.width)
    x-=dx;

to this: 对此:

// move the ball
x += dx;

if (x > htmlCanvas.width - 50) {
   // if we hit the right edge, get back in bounds
   x = htmlCanvas.width - 50;
   // and reverse direction
   dx *= -1;
} else if (x < 50) {
   // if we hit the left edge, get back in bounds
   x = 50;
   // and reverse direction
   dx *= -1;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM