Toggle navigation
☰
HTML
CSS
Scripting
Database
<!DOCTYPE html> <html> <body> <canvas id="hitCanvas" width="300" height="150" style="border:1px solid #d3d3d3;"></canvas> <p id="clickMsg">Click the rectangle!</p> <script> var canvas = document.getElementById("hitCanvas"); var ctx = canvas.getContext("2d"); var msg = document.getElementById("clickMsg"); // 1. Draw a rectangle ctx.beginPath(); ctx.rect(50, 25, 100, 100); ctx.fillStyle = "#FF8C00"; ctx.fill(); // 2. Add a click event listener canvas.addEventListener("click", function(event) { // Translate mouse coordinate to canvas coordinate var rect = canvas.getBoundingClientRect(); var x = event.clientX - rect.left; var y = event.clientY - rect.top; // 3. Check if the click was in the current path if (ctx.isPointInPath(x, y)) { msg.innerHTML = "You clicked the rectangle!"; ctx.fillStyle = "#0070C0"; ctx.fill(); } else { msg.innerHTML = "You missed the rectangle."; } }); </script> </body> </html>