简体   繁体   中英

Bouncing ball javascript

So I have an html page that has buttons for bouncing the ball, I want to ball to start in the middle when the page is loaded which is what it does. Then i want it to bounce when I push the button called bounce yet, when i click it it only moves 1 frame. Id like it to just keep bouncing.

html code

 <button type="button" onclick="bounce()">Bounce</button>

javascript function for the ball when button is clicked

var canvas;
var ctx;
var ballX = 250;
var ballY = 250;
var xVelocity = 2;
var yVelocity = 3;
var ballWidth = 50;

 //Gets Canvas + Sets Framerate
 window.onload = function() {
  canvas = document.getElementById("test");
 ctx = canvas.getContext("2d");
 setInterval(draw,1000/60);
}

//Draw EVERYTHING
function draw() {

//Color The Canvas white
ctx.fillStyle = "white";
ctx.fillRect(0,0,canvas.width,canvas.height);

//Draw The Ball
ctx.beginPath();
ctx.fillStyle = color;
ctx.strokeStyle = "black";
ctx.lineWidth = 2;
ctx.arc(ballX,ballY,ballWidth,0,Math.PI*2, true);
ctx.fill();
ctx.stroke();
ctx.closePath();

}

//Change Ball Position
function bounce()
{

 ballX += xVelocity;
 ballY += yVelocity;

 if(ballX - ballWidth <= 0) {
  xVelocity = -xVelocity;

}

//Bounce Ball Off Right 
if(ballX + ballWidth >= canvas.width) {
xVelocity = -xVelocity;

}

 //Bounce Ball Off Top
if(ballY - ballWidth <= 0) {
 yVelocity = -yVelocity;

}

//Bounce Ball Off Bottom 
if(ballY + ballWidth >= canvas.height) {
  yVelocity = -yVelocity;

}

}

your problem is because you need run bounce inside draw function, you need a flag to activate this function.

<button type="button" onclick="bounceFlag= true;">Bounce</button>

var bounceFlag = false;

and inside of draw

if(bounceFlag) {
    bounce()
}

you can see your example working here [ https://codepen.io/anon/pen/jQeRxM?editors=1010][

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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