Data visualization: interazione con i dati

Intercettando uno degli eventi gestiti da p5.js (ad es. con mouseMoved()) si può chiamare un metodo di tutte le istanze (ad es. checkMouse()) che può aggiornare una proprietà (ad es. underMouse) da leggere in fase di visualizzazione.

    class Stato {
    constructor(info) {
        this.info = info;                  
        let coord = info.latlng;         
        let x = map(coord[1], -180, 180, 0, width);  
        let y = map(coord[0], 90, -90, 0, height);   
        this.pos = createVector(x, y);   
    }
    display() {
        if (this.underMouse) {       // Se mouse sopra stato...
            let diametro = this.info.population/2000000; // Proporzionale
            circle(this.pos.x, this.pos.y, diametro);    // a popolazione
        } else {
            noFill();  
            circle(this.pos.x, this.pos.y, 2); 
        }                       
    }
    checkMouse(mousePos) {
        this.underMouse = this.pos.dist(mousePos) < 3;  // A meno di 3px?
    }
}
function mouseMoved() {
    let mousePos = createVector(mouseX, mouseY); // Vettore posiz. mouse
    for (let stato of stati) {       // Per ogni stato...
        stato.checkMouse(mousePos);  // Verifica sovrapposizione mouse
    }
}
let json;        
let stati = [];  

function preload() {
    let servizio = "https://restcountries.com/v3.1/all";
    let parametri = "?fields=name,latlng,population";  
    json = loadJSON(servizio + parametri);  
}
function setup() {
    createCanvas(600, 300);
    for (let indice in json) {
        let popolazione = json[indice].population; 
        if (popolazione > 15000000) { 
            stati.push( new Stato(json[indice]) );
        }
    }
}
function draw() {
    background(255);
    for (let stato of stati) {
        stato.display(); 
    }
}
  

Provare a far visualizzare il nome dello stato al passaggio del mouse con un colore diverso dal nero, ad esempio usando:

    

Per centrare orizzontalmente il nome dello stato, si può inserire un textAlign(CENTER) nel setup() o poco prima dell’istruzione text().