Estoy tratando de crear una forma de luna con lienzo. Por lo tanto, creé dos círculos: uno se llenó con mi color, otro se restó usando globalCompositionOperation: "destination-out" .
const moonCanvas = createCanvas(WIDTH, HEIGHT); const moonCtx = canvas.getContext("2d"); moonCtx.beginPath(); moonCtx.arc(WIDTH / 2, HEIGHT / 2, HEIGHT / 4, 0, 2 * Math.PI); moonCtx.fill(); moonCtx.globalCompositeOperation = "destination-out"; moonCtx.beginPath(); moonCtx.arc(WIDTH / 2 + 30, HEIGHT / 2, HEIGHT / 4, 0, 2 * Math.PI); moonCtx.fill();Aquí hay un violín con una reproducción mínima: https://jsfiddle.net/h2qbytzn/
El problema ahora es que esta operación agrega una transparencia "explícita" al lienzo. Cada vez que quiero agregar la luna a otro lienzo, también incluye las partes transparentes y, por lo tanto, sobrescribe lo que ya está allí en el lienzo.
¿Hay alguna forma de importar el contenido del lienzo ignorando las partes transparentes?
Lo que funcionó para mí ahora es crear un segundo lienzo, pintar mis objetos allí y fusionarlos en el lienzo original con drawImage :
const c2 = createCanvas(WIDTH, HEIGHT); const ctx2 = c2.getContext("2d"); ctx2.fillStyle = "yellow"; ctx2.beginPath(); ctx2.arc(WIDTH / 2, HEIGHT / 2, HEIGHT / 4, 0, 2 * Math.PI); ctx2.fill(); ctx2.globalCompositeOperation = "destination-out"; ctx2.beginPath(); ctx2.arc(WIDTH / 2 + 30, HEIGHT / 2 - 15, HEIGHT / 4, 0, 2 * Math.PI); ctx2.fill(); ctx.drawImage(c2, 0, 0); // merging the canvas, not its context!