青春纸盒子

文: 芦苇

你喜欢我笑的样子

我靠上了落寞的窗子

晚风吹起了我的袖子

明月沾湿了你的眸子


转身,你走出了两个人的圈子

树影婆娑,整座院子


挽起袖子

回头,把揽你忧伤一地的影子

装进,青春,这纸盒子


更多代码请关注我的微信小程序: "ecoder"

luwei0915

导航

canvas_04 碰撞检测

效果图:

 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>

 

posted on 2021-12-26 22:21  芦苇の  阅读(29)  评论(0编辑  收藏  举报