1 <!DOCTYPE html>
2 <html lang="it">
3 <head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <title>Esempio di isPointInPath</title>
7 <style>
8 body {
9 display: flex;
10 justify-content: center;
11 align-items: center;
12 height: 100vh;
13 margin: 0;
14 }
15 canvas {
16 border: 1px solid black;
17 }
18 </style>
19 </head>
20 <body>
21 <canvas id="canvas" width="500" height="500"></canvas>
22
23 <script>
24 const canvas = document.getElementById('canvas');
25 const ctx = canvas.getContext('2d');
26 let isFilled = false;
27
28 function drawShape() {
29 ctx.clearRect(0, 0, canvas.width, canvas.height); // Pulisce il canvas
30
31 ctx.beginPath();
32 ctx.moveTo(170, 80);
33 ctx.bezierCurveTo(130, 100, 130, 150, 230, 150);
34 ctx.bezierCurveTo(250, 180, 320, 180, 340, 150);
35 ctx.bezierCurveTo(420, 150, 420, 120, 390, 100);
36 ctx.bezierCurveTo(430, 40, 370, 30, 340, 50);
37 ctx.bezierCurveTo(320, 5, 250, 20, 250, 50);
38 ctx.bezierCurveTo(200, 5, 150, 20, 170, 80);
39 ctx.closePath();
40
41 if (isFilled) {
42 ctx.fillStyle = 'red';
43 ctx.fill();
44 } else {
45 ctx.strokeStyle = 'black';
46 ctx.lineWidth = 2;
47 ctx.stroke();
48 }
49 }
50
51 canvas.addEventListener('click', (event) => {
52 const x = event.offsetX;
53 const y = event.offsetY;
54
55 ctx.beginPath();
56 ctx.moveTo(170, 80);
57 ctx.bezierCurveTo(130, 100, 130, 150, 230, 150);
58 ctx.bezierCurveTo(250, 180, 320, 180, 340, 150);
59 ctx.bezierCurveTo(420, 150, 420, 120, 390, 100);
60 ctx.bezierCurveTo(430, 40, 370, 30, 340, 50);
61 ctx.bezierCurveTo(320, 5, 250, 20, 250, 50);
62 ctx.bezierCurveTo(200, 5, 150, 20, 170, 80);
63 ctx.closePath();
64
65 if (ctx.isPointInPath(x, y)) {
66 isFilled = !isFilled;
67 drawShape();
68 }
69 });
70
71 drawShape();
72 </script>
73 </body>
74 </html> |