## Canvas Animation: Random Bounce In a Box

| |
[ 所属分类 前端（javascript） | 发布者 店小二05 | 时间 2016 | 作者 红领巾 ] 0人收藏点击收藏

In thelast article I demonstrated literally straightforward animation, moving a square from one side of the canvas drawing element to the other. In this piece, I’ll show continuous motion of a circle in many different directions, a useful lesson in how to develop a complete javascript canvas animation:

Preparing the Canvas

The page starts with a <canvas> element :

<canvas id="drawspace" width="800" height="500"></canvas>

I’ll alsostyle the element, and make itresponsive:

#drawspace { background: #000; width: 100%; }

TheJavaScript, at the bottom of the page, starts by creating a shortcut to the drawing context of the canvas, then sets up aconstant for the radius of the circle that will be drawn on it, together withvariables that determine the circle’s initial position:

const ctx = drawspace.getContext("2d"), circRad = 100; let x = 150, y = 200; ctx.fillStyle = "yellow";

Drawing a circle in <canvas> is more complicated than drawing a rectangle: we need to start a path, create a closed arc, then end the path.

function drawCirc() { ctx.beginPath(); ctx.arc(x,y,circRad,0,2*Math.PI,true); ctx.closePath(); ctx.fill(); } drawCirc();

The parameters of the arc method can be a little confusing: the 0 defines the starting point for the arc, while the calculation at the end provides the closing point inrads . The true parameter defines the direction of the arc (clockwise or counter-clockwise) not relevant for making a closed circle, but a required parameter all the same.

Bounce

Right now, thefunction draws the circle at a fixed position. If we want to animate the circle, we need to change the value of x and/or y over time. And if we don’t want the circle to drift off the side of the canvas, we need to detect when the circle hits the edge, reversing the direction of travel when it does so. I’ll start by changing the motion of the ball on the x axis first.

Before we begin, we need to determine how much the ball moves during each moment of the animation. That’s controlled by two variables added to the start of the script:

let x = 150, y = 200, dx = 2, dy = 2;

The drawCirc function changes to:

function drawCirc() { ctx.clearRect(0, 0, drawspace.width, drawspace.height); ctx.arc(x,y,circRad,0,2*Math.PI,true); if (x < 0 || x > drawspace.width) { dx=-dx; } x+=dx; window.requestAnimationFrame(drawCirc); }

The function needs some explanation:

the clearRect cleans the canvas space before it is drawn on. bouncing ahead, the x variable has the value of dx added to it. just before that, there is a test: if x is less than 0 or greater than the width of the canvas, the sign of dx is flipped , equivalent to multiplying it by -1 : if the value of dx was positive, it turns negative, and if it was negative, it turns positive.

The result is that the ball will “bounce” between the vertical edges of the canvas: when it hits the right wall, the flipped sign of dx will result in x being subtracted from, heading the ball to the left.

One problem is that the ball will go too far: half of the ball will disappear over each edge, since the circle’s position is always measured from its center . We can correct that, using a variable we defined earlier:

if (x < circRad || x > drawspace.width - circRad) { … }

We can use the same approach for vertical movement. The function changes to:

function drawCirc() { ctx.clearRect(0, 0, box.width, box.height); ctx.drawImage(img, x, y, img.width, img.height); if (x < circRad || x > drawspace.width - circRad) { dx=-dx; } if (y < circRad || y > drawspace.width - circRad) { dy=-dy; } x+=dx; y+=dy; window.requestAnimationFrame(drawCirc); }

The result is a animated ball bouncing randomly inside the area of the canvas. The angle of those bounces and the speed of travel can be changed by altering the value of dx and dy .

This code can be used in many different ways, as you can see in the associated CodePen demo .

Since you know when the ball hits any of the internal walls of the canvas area, you could do anything at that moment: change the color of the ball, start it in a random location, play a sound through the Web Audio API, etc. I’ll be demonstrating a few of those possibilities in the next article.

1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责；
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性，不作出任何保证或承若；
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。