跳跳球 <script> <br>//box <br>var box_x=0; <br>var box_y=0; <br>var box_width=300; <br>var box_height=300; <br>//注意:定位球采用球的中心 <br>var ball_x=10; <br>var ball_y=10; <br>var ball_radius=10; <br>var ball_vx=5; <br>var ball_vy=3; <br>var box_bound_left=box_x ball_radius; <br>var box_bound_right=box_x box_width-ball_radius; <br>var box_bound_top=box_y ball_radius; <br>var box_bound_bottom=box_y box_height-ball_radius; <br>//ball <br>//context <br>var ctx; <br>function init() <br>{ <br>ctx=document.getElementById('canvas').getContext('2d'); <br>ctx.lineWidth=ball_radius; <br>ctx.fillStyle="rgb(200,0,50)"; <br>move_ball(); <br>setInterval(move_ball,100);//note <br>} <br>function move_ball() <br>{ <br>ctx.clearRect(box_x,box_y,box_width,box_height); <br>move_and_check(); <br>ctx.beginPath(); <br>ctx.arc(ball_x,ball_y,ball_radius,0,Math.PI*2,true); <br>ctx.fill(); <br>ctx.StrokeRect(box_x,box_y,box_width,box_height); <br>} <br>function move_and_check() <br>{ <br>var cur_ball_x=ball_x ball_vx; <br>var cur_ball_y=ball_y ball_vy; <br>if(cur_ball_x<box_bound_left) <br />{ <br />ball_vx=-ball_vx; <br />cur_ball_x=box_bound_left; <br />} <br />if(cur_ball_x>box_bound_right) <br>{ <br>ball_vx=-ball_vx; <br>cur_ball_x=box_bound_right; <br>} <br>if(cur_ball_y<box_bound_top) <br />{ <br />ball_vy=-ball_vy; <br />cur_ball_y=box_bound_top; <br />} <br />if(cur_ball_y>box_bound_bottom) <br>{ <br>ball_vy=-ball_vy; <br>cur_ball_y=box_bound_bottom; <br>} <br>ball_x=cur_ball_x; <br>ball_y=cur_ball_y; <br>} <br></script>