How to realize the bouncing ball in the frame by JavaScript+canvas
This article mainly explains "how to realize the bouncing ball in the frame by JavaScript+canvas". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "how to achieve the bouncing ball in the frame by JavaScript+canvas"!
The effect is as follows:
Train of thought:
1. Draw up the canvas and determine the coordinates
two。 Draw a round ball
3. Give the circle an original coordinate, the speed of the xy axis.
4. Refresh every 20 milliseconds to achieve the purpose of change
5. Judge the edge
All the codes and definitions are as follows:
Document's current browser does not support canvas. Please update your browser or upgrade your browser and try again / / x: ball original x coordinate, y: ball original y coordinate, r: ball radius, vx: X axis speed, vy: y axis speed (speed is all expressed as a vector, so it can be negative) var ball = {x: 512, y: 100, r: 20, vx:-8, vy: 8 Color:'# 005588'} _ window.onload = function () {var canvas = document.getElementById ("canvas") / / define the size of canvas canvas canvas.width = 860; canvas.height = 600; / / determine whether the browser supports canvas if (canvas.getContext ("2d")) {/ / all the functions called below are based on the context of context, var context = canvas.getContext ("2d") SetInterval (() = > {render (context) update ()}, 20);} else {alert ("the current browser does not support canvas, please update your browser or upgrade your browser and try again");}}; / / hexadecimal color random function color16 () {var r = Math.floor (Math.random () * 256) Var g = Math.floor (Math.random () * 256); var b = Math.floor (Math.random () * 256); var color ='#'+ r.toString (16) + g.toString (16) + b.toString (16); return color } / / Refresh function update () {ball.x + = ball.vx / / x axis coordinates vx is the speed of x axis, uniform increase ball.y + = ball.vy / / y axis coordinates due to g If (ball.y > = canvas.height-ball.r) {ball.color = color16 () ball.y = canvas.height-ball.r / / bottom ball.vy =-ball.vy} else if (ball.x = canvas.width-ball.r) {ball.color = color16 () Ball.x = canvas.width-ball.r / / right-touch ball.vx =-ball.vx} else if (ball.y