I want to generate a set of text elements inside a triangle bounded by preset coordinates. For example; something like this. Note that the text should be inside the pink triangle. (It is okay if the text clips the triangle's lines since the triangle will be invisible in the final product, this is just for reference)
To achieve this I created the following codepen.
The random generation inside specified boundaries works fine, but since its possible for the same or very close coordinates to be generated, sometimes the text overlaps.
Is there any possible approach I could take to fix/avoid this issue efficiently?
function randomIntFromInterval(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min)
}
function area(x1, y1, x2, y2, x3, y3) {
return Math.abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0);
}
function isInside(x1, y1, x2, y2, x3, y3, x, y) {
let A = area(x1, y1, x2, y2, x3, y3);
let A1 = area(x, y, x2, y2, x3, y3);
let A2 = area(x1, y1, x, y, x3, y3);
let A3 = area(x1, y1, x2, y2, x, y);
return (A == A1 + A2 + A3);
}
let canvas = document.querySelector('canvas')
const CANVAS_SIZE = 300
canvas.width = CANVAS_SIZE
canvas.height = CANVAS_SIZE
const ctx = canvas.getContext('2d');
let arrayOfText = ['A', 'B', 'C', 'D']
ctx.beginPath();
ctx.moveTo(25, 25);
ctx.lineTo(225, 25);
ctx.lineTo(225, 225);
ctx.lineTo(25, 25);
ctx.strokeStyle = "#bb0874"
ctx.stroke()
ctx.font = `600 14px Arial`;
for (let i = 0; i < (arrayOfText.length); i++) {
while (true) {
let x = randomIntFromInterval(40, 180)
let y = randomIntFromInterval(15, 160)
if (isInside(25, 25, 225, 25, 225, 225, x, y)) {
ctx.fillText(arrayOfText[i], x, y);
break;
}
}
}
canvas {
border: 1px solid black;
}
<body>
<canvas></canvas>
</body>