Javascript球无限期地来回弹跳

时间:2016-08-20 21:15:12

标签: javascript

我正在编写一个简单的JS函数,它可以在画布中绘制一个球,并且可以无限期地在屏幕的左右边界之间来回反弹。我现在从左侧开始向右走。我现在如何拥有它,它向右移动然后卡在右边缘;它没有反弹。有什么提示吗?

        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); 

1 个答案:

答案 0 :(得分:2)

改变这个:

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

到此:

// 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;
}