HTML - HTML5JavaScriptSviluppo

Creare e rilevare la connessione di rete mobile con canvas e javascript

Creare e rilevare la connessione di rete mobile con canvas e javascript

 

Se vogliamo creare un’icona che cambia e rileva il tipo di connessione di rete mobile (da 3G a 4G oppure da 2G a 4G e così via) possiamo sfruttare javascript e canvas per la parte grafica. Per facilitare la creazione di tale codice, qui sotto troverete la mia versione:

<canvas class="networkConnection" style="width:600px; height:600px;"></canvas>

<script>
var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
var type = connection.effectiveType;

function updateConnectionStatus() {
   type = connection.effectiveType;
   online();
}

var canvasNC = document.getElementsByClassName("networkConnection")[0];
var ctxNC = canvasNC.getContext("2d");

connection.addEventListener('change', updateConnectionStatus);
online();

const status = window.navigator.onLine;
if (status)
   online();
else
   offline();

window.addEventListener('online', online);
window.addEventListener('offline', offline);

function online() {
   if (type === "4g") {
      ctxNC.clearRect(0, 0, canvasNC.width, canvasNC.height);
      ctxNC.fillStyle = "#00DD00";
      ctxNC.fillRect(0, 100, 90, 200);
      ctxNC.fillStyle = "#00DD00";
      ctxNC.fillRect(100, 50, 90, 200);
      ctxNC.fillStyle = "#00DD00";
      ctxNC.fillRect(200, 0, 90, 200);
   }
   if (type === "3g") {
      ctxNC.clearRect(0, 0, canvasNC.width, canvasNC.height);
      ctxNC.fillStyle = "#00DD00";
      ctxNC.fillRect(0, 100, 90, 200);
      ctxNC.fillStyle = "#00DD00";
      ctxNC.fillRect(100, 50, 90, 200);
   }
   if (type === "2g") {
      ctxNC.clearRect(0, 0, canvasNC.width, canvasNC.height);
      ctxNC.fillStyle = "#00DD00";
      ctxNC.fillRect(0, 100, 90, 200);
   }
}

function offline() {
   ctxNC.clearRect(0, 0, canvasNC.width, canvasNC.height);
   ctxNC.fillStyle = "#AAAAAA";
   ctxNC.fillRect(0, 100, 90, 200);
   ctxNC.fillStyle = "#AAAAAA";
   ctxNC.fillRect(100, 50, 90, 200);
   ctxNC.fillStyle = "#AAAAAA";
   ctxNC.fillRect(200, 0, 90, 200);
}
</script>

/ 5
Grazie per aver votato!

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *