簡體   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