弹跳球JavaScript

时间:2018-11-28 23:56:46

标签: javascript html

因此,我有一个html页面,该页面具有用于弹起球的按钮,我希望球在页面加载时从中间开始,这就是它的作用。然后,当我按“弹跳”按钮时,我希望它弹跳,当我单击它时,它只能移动1帧。我希望它不断弹跳。

html代码

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

单击按钮时球的javascript功能

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;

}

}

1 个答案:

答案 0 :(得分:0)

您的问题是因为您需要在draw函数中运行反弹,因此需要一个标志来激活此功能。

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

var bounceFlag = false;

在抽奖中

if(bounceFlag) {
    bounce()
}

您可以在此处查看示例[https://codepen.io/anon/pen/jQeRxM?editors=1010][