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