Example code of html5 Bouncing Ball

Source: Internet
Author: User

Comments: You can use html5 to implement the bounce ball. You can use html5 to implement it. The specific code and code are as follows. If you are interested, please refer to the following link and hope to help you.

The Code is as follows:
<Html>
<Head>
<Meta charset = UTF-8>
<Title> Jump ball </title>
<Script>
// Box
Var box_x = 0;
Var box_y = 0;
Var box_width = 300;
Var box_height = 300;
// Note: The positioning ball uses the center of the ball.
Var ball_x = 10;
Var ball_y = 10;
Var ball_radius = 10;
Var ball_vx = 5;
Var ball_vy = 3;
Var box_bound_left = box_x + ball_radius;
Var box_bound_right = box_x + box_width-ball_radius;
Var box_bound_top = box_y + ball_radius;
Var box_bound_bottom = box_y + box_height-ball_radius;
// Ball
// Context
Var ctx;
Function init ()
{
Ctx = document. getElementById ('canvas '). getContext ('2d ');
Ctx. lineWidth = ball_radius;
Ctx. fillStyle = "rgb (200,0, 50 )";
Move_ball ();
SetInterval (move_ball, 100); // note
}
Function move_ball ()
{
Ctx. clearRect (box_x, box_y, box_width, box_height );
Move_and_check ();
Ctx. beginPath ();
Ctx. arc (ball_x, ball_y, ball_radius, 0, Math. PI * 2, true );
Ctx. fill ();
Ctx. strokeRect (box_x, box_y, box_width, box_height );
}
Function move_and_check ()
{
Var cur_ball_x = ball_x + ball_vx;
Var cur_ball_y = ball_y + ball_vy;
If (cur_ball_x <box_bound_left)
{
Ball_vx =-ball_vx;
Cur_ball_x = box_bound_left;
}
If (cur_ball_x> box_bound_right)
{
Ball_vx =-ball_vx;
Cur_ball_x = box_bound_right;
}
If (cur_ball_y <box_bound_top)
{
Ball_vy =-ball_vy;
Cur_ball_y = box_bound_top;
}
If (cur_ball_y> box_bound_bottom)
{
Ball_vy =-ball_vy;
Cur_ball_y = box_bound_bottom;
}
Ball_x = cur_ball_x;
Ball_y = cur_ball_y;
}
</Script>
</Head>
<Body onLoad = "init ()">
<Canvas id = "canvas" width = "400" height = "400"/>
</Body>
</Html>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.