canvas_17 下落的小鸟
效果图:
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 * { 11 margin: 0; 12 padding: 0; 13 } 14 15 html, 16 body { 17 height: 100%; 18 } 19 20 canvas { 21 background-color: #EEEEEE; 22 } 23 </style> 24 </head> 25 26 <body> 27 28 <canvas id="canvas"></canvas> 29 30 <script> 31 var canvas = document.querySelector("#canvas"); 32 var ctx = canvas.getContext("2d"); 33 canvas.width = window.innerWidth; 34 canvas.height = window.innerHeight; 35 36 var x = 200; 37 var y = 100; 38 // 总帧 39 var fno = 0; 40 // 下落的帧 41 var dropFno = 0; 42 var deg = -0.6; 43 var isClick = false; 44 var image = new Image(); 45 // size: 48 * 48 46 image.src = "../static/images/bird0_0.png"; 47 image.onload = function() { 48 setInterval(function() { 49 ctx.clearRect(0, 0, canvas.width, canvas.height); 50 fno++; 51 deg += 0.03 52 ctx.font = "20px 微软雅黑"; 53 ctx.fillText(fno, 10, 30); 54 55 // 鼠标没有点击,自由落体 56 if (!isClick) { 57 y += 0.4 * dropFno; 58 } else { 59 // 鼠标点击,速度反向,上升20帧 60 y -= 0.4 * (20 - dropFno); 61 if (dropFno > 20) { 62 isClick = false; 63 dropFno = 0; 64 } 65 // 不能上升到屏幕外 66 if (y < 0) { 67 y = 0; 68 } 69 } 70 dropFno++; 71 ctx.save(); 72 73 // 不管上升还是下降,都要旋转(俯冲) 74 ctx.translate(x + 24, y + 24); 75 ctx.rotate(deg); 76 ctx.fillText(dropFno, -24, -24); 77 ctx.drawImage(image, -24, -24); 78 ctx.restore(); 79 }, 20) 80 } 81 82 // 鼠标点击,小鸟方向直接回正,重新计算加速度 83 canvas.onclick = function() { 84 isClick = true; 85 dropFno = 0; 86 deg = -0.6; 87 } 88 </script> 89 </body> 90 91 </html>