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
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Canvas 拾取点示例</title> <style> canvas { border: 1px solid black; } </style> </head> <body> <canvas id="myCanvas" width="400" height="400"></canvas> <script>
var canvas = document.getElementById('myCanvas'); var ctx = canvas.getContext('2d');
var rectangle = { x: 50, y: 50, width: 100, height: 100, fillStyle: 'blue' };
function drawRectangle() { ctx.fillStyle = rectangle.fillStyle; ctx.fillRect(rectangle.x, rectangle.y, rectangle.width, rectangle.height); }
canvas.addEventListener('click', function(event) { var x = event.clientX - canvas.offsetLeft; var y = event.clientY - canvas.offsetTop; if (x > rectangle.x && x < rectangle.x + rectangle.width && y > rectangle.y && y < rectangle.y + rectangle.height) { ctx = canvas.getContext('2d'); rectangle = { x: 50, y: 50, width: 100, height: 100, fillStyle: 'red' }; ctx.fillStyle = rectangle.fillStyle; ctx.fillRect(rectangle.x, rectangle.y, rectangle.width, rectangle.height); } else { rectangle = { x: 50, y: 50, width: 100, height: 100, fillStyle: 'blue' }; ctx.fillStyle = rectangle.fillStyle; ctx.fillRect(rectangle.x, rectangle.y, rectangle.width, rectangle.height); } });
drawRectangle(); </script> </body> </html>
|