Canvas: a bounce ball

Source: Internet
Author: User

The first blog in 2014

Recently, I am reading the canvas of html5. For a child who does not know how to develop flash, I am still dedicated to canvas. Who is flash. This example is very simple, that is, a simple elastic ball continuously jumps in a box.

It consists of two parts: an elastic ball and a box defining the scope.

First, use the arc function of canvas to draw a ball.

ctx.beginPath();                ctx.arc(ballX, ballY, ballRad, 0, Math.PI * 2, false);                ctx.fill();
Draw a border with strokeRect

ctx.strokeRect(boxX, boxY, boxWidth, boxHeight);

Check the ball position ballX and ballY every Ms. If the ball position exceeds the border, the corresponding motion direction is reversed.

// Function for determining the distance function changDirect () {var nextX = ballX + ballVX, nextY = ballY + ballVY; if (nextX> boxRoundX) {ballVX =-ballVX; nextX = boxRoundX;} if (nextX <inboxRoundX) {ballVX =-ballVX; nextX = inboxRoundX;} if (nextY> boxRoundY) {ballVY =-ballVY; nextY = boxRoundY ;} if (nextY <inboxRoundY) {ballVY =-ballVY; nextY = inboxRoundY;} ballX = nextX; ballY = nextY ;}
Finally, clear the canvas and re-draw the ball and border pattern at intervals of 100 ms based on the current coordinate position.

Shows the effect:

You can also replace the ball with an image in your local folder.

Var img = new Image (); img. src = 'image/1.jpg '; // draw the image ctx. drawImage (img, ballX-ballRad, ballY-ballRad, 2 * ballRad, 2 * ballRad );
For source code and comments, visit my github: https://github.com/chenkehxx/practice/commit/65067f7bb7948abe94b052f3e69fc2b1892ab167

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.