This article mainly introduces the native js method and code sharing for making a simple Jump ball with html5. We recommend this article to you. If you need it, you can refer to it. Demo address: http://runjs.cn/detail/yjpvqhal
Html code
Xiao feilong's dance ball
Your browser does not support html5 Canvas elements. Please upgrade to IE9 + or use advanced intelligent browser such as firefox and chrome!
Script var canvas = document. getElementById ('game'); var ctx = canvas. getContext ('2d '); var grad; // the start position and size of the box and the ball radius var box = {x: 20, y: 20, w: 350, h: 350, r: 20}; // the center position and offset position of the ball. var inbox = {// The restriction range in the box is bx :( box. w + box. x-box.r), by :( box. h + box. y-box.r), ix: box. x + (box. r * 2), iy: box. y + (box. r * 2)}; // The initial position and change position of the ball var ball = {x: 50, y: 50, vx: 4, vy: 8 }; var img = new Image (); img. src = 'images/qiuqiu.png '; var hue = [[255,255, 0], [0,255, 0], [0,255,255, 0], [255], [,], [255, 0, 0]; function init () {grad = ctx. createLinearGradient (box. x, box. y, box. w, box. h); for (var I = 0; I
Inbox. bx) {// The current x is greater than the upper border ball. vx =-ball. vx; // ball change x coordinate current change x coordinate negative nx = inbox. bx; // The current position is the position of the upper border} if (nx <inbox. ix) {// The current position is smaller than the bottom Frame nx = inbox. ix; // The current position is the x ball in the lower border. vx =-ball. vx; // ball change x coordinate flip take negative} if (ny> inbox. by) {ny = inbox. by; ball. vy =-ball. vy;} if (ny <inbox. iy) {ny = inbox. iy; ball. vy =-ball. vy;} ball. x = nx; ball. y = ny;} function moveBall () {ctx. clearRect (box. x, box. y, box. w, box. h); moveBallEndCheck (); ctx. beginPath (); // console. log (ball. x + "\ t" + ball. y + "\ t" + ball. vx + "\ t" + ball. vy + "\ t" + (ball. x-box.r) + "\ t" + (ball. y-box.r); ctx. drawImage (img, (ball. x-box.r), (ball. y-box.r); ctx. fillRect (box. x, box. y, box. r, box. h); ctx. fillRect (box. x + box. w-box.r), box. y, box. r, box. h); ctx. fillRect (box. x, box. y, box. w, box. r); ctx. fillRect (box. x, (box. y + box. h-box.r), box. w, box. r); ctx. closePath (); ctx. fill ();} script
Demo Image
The above is all the code in this article. I hope you will like it.