Actualmente estoy trabajando con la generación de imágenes y me he topado con un problema que me ha dejado perplejo durante unas horas. Aquí hay una breve explicación. Abajo hay dos fotos de perfil (tributos) con sus respectivos distritos flotando sobre ellas. En el caso de dos tributos, el texto del distrito se centrará sobre ellos como se muestra a continuación.
En el caso de más de dos, los dos primeros tributos deben tener el Distrito centrado entre ellos, mientras que la última persona lo tiene centrado sobre ellos.
En términos de código, he encontrado una manera de detectar tales casos. Pero no he descubierto cómo textDestinationX podría usar el bucle para calcular la posición deseada del texto.
drawDistrictText(ctx, tributeArray) { ctx.font = 'bold 28px arial'; ctx.textBaseline = 'alphabetic'; ctx.fillStyle = '#ffffff'; ctx.textAlign = 'center'; const districtCount = Math.max(Math.ceil(tributeArray.length / 2), 2); let textDestinationX; let textDestinationY = avatarPaddingY - 15; for (let i = 0; i < districtCount; i++) { const districtText = `District ${i + 1}`; /* detecting if we are on our last iteration, and if the total length is odd, meaning there must be a district with one user. or if there is only 2 tributes. */ if ((i === districtCount - 1 && tributeArray.length % 2 === 1) || tributeArray.length === 2) { console.log('center'); } else { console.log('between'); } /* After every 6 tributes, Y position is shifted down for the next row. The X position would need to be set to it's original position. */ if ((i + 1) % 3 === 0) { textDestinationY += avatarSize + avatarSpacingY; } } }