【发布时间】:2018-11-29 08:22:09
【问题描述】:
所以我有一个 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;
}
}
【问题讨论】:
-
您的
bounce()是移动球的动力。调用它一次将使球移动几个像素。听起来您希望球在单击按钮时开始移动?在这种情况下,您需要 a) 将初始速度设置为零 b)bounce()球每帧,如draw()c) 当您单击按钮时将速度设置为非零:jsfiddle.net/khrismuc/w2km0x47
标签: javascript html