1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>小球碰撞检测</title> <style> canvas{ border: 2px solid grey; display: block; margin: 0 auto; } </style> </head> <body> <canvas width="500px" height="500px" id="canvas"></canvas> <script> let canvas = document.querySelector('#canvas'); let ctx = canvas.getContext('2d'); let drawCircle = function(x,y,r,start,end,flag){ ctx.beginPath(); ctx.arc(x,y,r,start,end,flag); ctx.fillStyle = 'gold'; ctx.fill(); ctx.stroke(); } let x = 100; let y = 100; let Xspeed = 10*Math.random(); let Yspeed = 10*Math.random(); let r = 30; setInterval(()=>{ ctx.clearRect(0,0,500,500);
if((x+r>=500)||(x-r)<=0){ Xspeed = -Xspeed; } if((y+r>=500)||(y-r)<=0){ Yspeed = -Yspeed; } x = x+Xspeed; y = y+Yspeed; drawCircle(x,y,r,0,2*Math.PI,true) },20) </script> </body> </html>
|