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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
| <!DOCTYPE html> <html> <head> <title>Canvas</title> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style> canvas { background: #eee; } </style> </head>
<body> <h1>Interaction</h1> <canvas class="canvas" width="600" height="400"></canvas>
<script src="utils.js"></script> <script src="Box.js"></script> <script src="Panel.js"></script> <script> const canvas = document.querySelector(".canvas"); const context = canvas.getContext("2d"); const boxes = []; const mousePos = { x: 0, y: 0 }; let panel; let selectedBox; let oX; let oY; let step; let rafId;
context.font = "bold 30px sans-serif";
function render() { context.clearRect(0, 0, canvas.width, canvas.height);
let box; for (let i = 0; i < boxes.length; i++) { box = boxes[i]; box.draw(); }
switch (step) { case 1: for (let i = 0; i < boxes.length; i++) { box = boxes[i]; box.x += box.speed; if (box.x > canvas.width) { box.x = -box.width; } } break;
case 2: panel.scale = panel.scale + (1 - panel.scale) * 0.1; panel.angle = panel.scale * 720; panel.draw(); if (panel.scale >= 0.999) { panel.scale = 1; panel.angle = 720; step = 3; } break;
case 3: panel.draw(); break; }
rafId = requestAnimationFrame(render); if (step === 3) { panel.showContent(); cancelAnimationFrame(rafId); } }
let tempX, tempY, tempSpeed;
function init() { step = 1; oX = canvas.width / 2; oY = canvas.height / 2; for (let i = 0; i < 10; i++) { tempX = Math.random() * canvas.width * 0.8; tempY = Math.random() * canvas.height * 0.8; tempSpeed = Math.random() * 4 + 1; boxes.push(new Box(i, tempX, tempY, tempSpeed)); }
panel = new Panel();
render(); }
canvas.addEventListener("click", (e) => { mousePos.x = e.layerX; mousePos.y = e.layerY;
let box; for (let i = 0; i < boxes.length; i++) { box = boxes[i]; if ( mousePos.x > box.x && mousePos.x < box.x + box.width && mousePos.y > box.y && mousePos.y < box.y + box.height ) { selectedBox = box; } }
if (step === 1 && selectedBox) { step = 2; } else if (step === 3) { step = 1; panel.scale = 0.01; selectedBox = null; render(); } });
init(); </script> </body> </html>
|