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