繁体   English   中英

弹跳球JavaScript

[英]Bouncing ball javascript

因此,我有一个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;

}

}

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

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

var bounceFlag = false;

在抽奖中

if(bounceFlag) {
    bounce()
}

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

暂无
暂无

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

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