Вы должны оценить, наведена ли мышь на текст. Положение мыши можно определить с помощью mouseX
и mouseY
. Высота текста устанавливается textSize
, а ширина текста может быть получена textWidth
. Например:
textH = 20
textSize(textH);
text('United States', 230, 260);
textW = textWidth('United States')
if (mouseX > 230 && mouseX < 230+textW && mouseY < 260 && mouseY > 260-textH) {
text('text', 230, 260+5+textH);
}
См. пример, где код используется в функции (textExpand
):
let maxDiameter;
let theta;
setup = () => {
createCanvas(1500, 600);
maxDiameter = 45;
theta = 0;
background(0);
ellipseMode();
}
textExpand = (textMain, textAdd, textX, textY, textH) => {
textSize(textH);
text(textMain, textX, textY);
textW = textWidth(textMain)
if (mouseX > textX && mouseX < textX+textW && mouseY < textY && mouseY > textY-textH) {
text(textAdd, textX, textY+5+textH);
}
}
draw = () => {
background(0);
fill(255, 0, 0, 255);
noStroke();
textH = 20
textSize(textH);
fill(255, 0, 0, 255);
//United States
var diam = 10 + sin(theta) * maxDiameter;
fill(132, 132, 132, 200);
stroke(132, 132, 132, 200);
textExpand('United States', 'test1', 230, 260, 20);
ellipse(200, 240, diam, diam);
//Morocco
fill(0, 255, 0, 200);
stroke(0, 255, 0, 200);
textExpand('Morocco', 'test2', 500, 300, 20);
ellipse(590, 315, diam, diam);
//Canada
fill(253, 100, 1, 200);
stroke(253, 100, 1, 200);
textExpand('Canada', 'test3', 260, 140, 20);
ellipse(230, 140, diam, diam);
//Russian Federation
fill(132, 132, 132, 200);
stroke(132, 132, 132, 200);
textExpand('Russian Federation', 'test4', 1030, 130, 20);
ellipse(1000, 125, diam, diam);
//Japan
fill(255, 0, 0, 200);
stroke(255, 0, 0, 200);
textExpand('Japan', 'test5', 1330, 245, 20);
ellipse(1295, 245, diam, diam);
theta += 0.03;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.10.2/p5.js"></script>