Quiero usar javascript para sombrear partes específicas de los dibujos de lienzo al hacer clic. Aquí está mi código a continuación que dibuja un cuadrado dentro de un círculo.
<!DOCTYPE HTML> <html> <head> </head> <body> <canvas width="300" height="300" id="myCanvas" style="border:1px solid #000000;"></canvas> <script> const canvas = document.getElementById('myCanvas'); const context = canvas.getContext('2d'); const centerX = canvas.width / 2; const centerY = canvas.height / 2; const radius = 70; context.beginPath(); context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false); context.rect(centerX-25, centerY-25, 50, 50) context.lineWidth = 5; context.strokeStyle = '#003300'; context.stroke(); </script> </body> </html>Y después de hacer clic en el área fuera del cuadrado pero aún dentro del círculo, solo quiero sombrear esa parte y tener algo como esto:
Simplemente puede llamar a fill() con la regla de llenado "evenodd" .
Sin embargo, esto cubrirá la mitad interna de su trazo actual, ya que para evitar eso, puede usar la composición para dibujar detrás de los dibujos actuales:
const canvas = document.getElementById('myCanvas'); const context = canvas.getContext('2d'); const centerX = canvas.width / 2; const centerY = canvas.height / 2; const radius = 70; context.beginPath(); context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false); context.rect(centerX-25, centerY-25, 50, 50) context.lineWidth = 5; context.strokeStyle = '#003300'; context.stroke(); context.fillStyle = "green"; canvas.onclick = ({ clientX, clientY }) => { const { left, top } = canvas.getBoundingClientRect(); // if we're in the circle but not the inner rect if( context.isPointInPath( clientX - left, clientY - top, "evenodd" ) ) { // draw behind context.globalCompositeOperation = "destination-over"; context.fill("evenodd"); // do it only once canvas.onclick = null; } }; <canvas width="300" height="300" id="myCanvas" style="border:1px solid #000000;"></canvas>