Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

javascript - How do you get the ball to bounce Y position

Making js animations and it will not bounce off the bottom of the screen, i am clue-less made with js and html Made by: hex

~js & html~


    var canvas = document.querySelector('canvas');

    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;


    var c = canvas.getContext('2d');


    var x = Math.random() * innerWidth;
    var y = Math.random() * innerHeight;
    var dx = (Math.random() - 0.5) * 3;
    var dy = (Math.random()  - 0.5) * 3;
    var radius = 30;
    function animate(){
      requestAnimationFrame(animate);
      c.clearRect(0, 0, innerWidth, innerHeight );
     
      c.beginPath();
      c.arc(x, y,  radius, 0, Math.PI* 2, false);
      c.strokeStyle = 'darkblue';
      c.stroke();
      
      if (x + radius > innerWidth || x - radius < 0){
          dx = -dx;
      }
      

      if (y + radius > innerHeight || y - radius < 0){
      dy += -dy;
      
    }

    x += dx;
    y += dy;
    }
    animate();


    console.log(innerHeight);
```
here is html
```

    <!DOCtype html>
    <html lang="en">
      <head>
        <meta charset="UTF-8">
        <title>Animation</title>
        <style type="text/css">
          canvas {
            border:1px solid black;
            background:white;
          }
          
          body {
            margin: 0;
          }
          
        </style>
      </head>
      
      <body>
        <canvas></canvas>
        <script src="Canvas.js"></script>
      </body>
    </html>

```

What did I do wrong????? I am learning js animation, and there is a error with Y Here is the code I have checked threw the code lots of times, yet I cant find what I did wrong, it says no errors and it seems to work, then just sticks to the bottom of the age, why?

question from:https://stackoverflow.com/questions/65848904/how-do-you-get-the-ball-to-bounce-y-position

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...