请大神们看看JS程序代码设置一个球运动,反弹怎么运行不出来,看上去很简单,就是运行不出来

JavaScript013

请大神们看看JS程序代码设置一个球运动,反弹怎么运行不出来,看上去很简单,就是运行不出来,第1张

帮你改了一下,能跑起来了。嗯.......你这个有一些语法问题和拼写不仔细的地方,估计太着急,有些粗心了~

<!DOCTYPE html>

<html>

<head>

<title>canvas</title>

<style>

*{

padding: 0

margin: 0

}

#container{

height: 80vh

width: 80vw

margin-top: 10vh

margin-left: 10vw

border: 1px solid #aaff66

}

</style>

</head>

<body>

<div id="container">

<canvas id="canvas"></canvas>

</div>

</body>

<script type="text/javascript">

window.onload = function() {

var ctx = document.getElementById('canvas').getContext('2d')

var circle = function(x, y, radius, fillCircle) {

ctx.beginPath()

ctx.arc(x, y, radius, 0, Math.PI * 2, false)

ctx.closePath()

ctx.fillStyle="green"

if (fillCircle) {

ctx.fill()

} else {

ctx.stroke()

}

}

var width=canvas.width = document.getElementById('container').offsetWidth

var height=canvas.height = document.getElementById('container').offsetHeight

var Ball=function(){

this.x=width/2

this.y=height/2

this.xSpeed = 5

this.ySpeed=0

}

Ball.prototype.move=function(){

this.x+=this.xSpeed

this.y+=this.ySpeed

if(this.x<0){

this.x=width

}else if(this.x>width){

this.x=0

}else if(this.y<0){

this.y=height

}else if(this.y>height){

this.y=0

}

}

Ball.prototype.draw=function(){

circle(this.x,this.y,10,true)

}

var ball= new Ball()

setInterval(function(){

ctx.clearRect(0,0,width,height)

ball.draw()

ball.move()

},30)

}

</script>

</html>

你好,

可以通过判断小球边缘和窗口高度来实现

例如垂直下落,给小球y方向的初速度和加速度(模拟重力加速度),当小球的小边缘接触窗口底部时,将 y = -y;加速度不反向;当达到最高点及y方向速度为零,将y再反向向下落。

来回弹动关键在于 对边缘的判断,和速度方向的判断和计算