Ubidots Developer Guides
Help CenterAPI ReferenceData APICommunity
  • Welcome to our Dev Guides
  • ⚡️ Getting Started
    • What is Ubidots?
    • Devices, Variables, and Dots
    • Technical FAQs
    • Business FAQs
  • 🧩Integration Guides
    • Industrial IoT
      • Advantech
      • Amplified Engineering
      • AWS
      • Azimut
      • Balena
      • Bivocom
      • CESVA
      • Controllino
      • Digital Communications Technologies (DCT)
      • Everactive
      • Golioth
      • Kepware
      • Kunbus
      • Monnit
      • MultiTech
      • NCD.io
      • Node-RED
      • Omicron IoT
      • Red Lion
      • Robustel
      • Senquip
      • Sielco
      • Siemens
      • Strega
      • vNode
      • WAGO
      • Weintek
      • YuDash
    • Cellular
      • Blues Wireless
      • Digi International
      • Hologram
      • Monogoto
      • Particle
      • Quectel
      • Soracom
    • LoRaWAN
      • AonChip
      • Chirpstack
      • Decentlab
      • Helium
      • ioThings
      • LORIOT
      • Milesight
      • MOKOSmart
      • RAKwireless
      • Sagemcom
      • Seeed Studio
      • Senet
      • The Things Industries
        • The Things Stack
        • The Things Network
    • Sigfox
      • Digital Matter
      • McThings
      • Sigfox
      • Suntech
      • Thinxtra
      • UnaBiz
    • Satellite
      • Swarm
    • Dev Kits
      • Adafruit
      • Advantech
      • AloriumTech
      • Arduino
      • Blues Wireless
      • DFRobot
      • Dragino
      • Electric Imp
      • Espressif Systems
      • McThings
      • Microchip Technology
      • Onion
      • Particle
      • Pycom
      • RAKwireless
      • Raspberry Pi
      • Seeed Studio
      • Sodaq
      • STMicroelectronics
      • Texas Instruments
      • Thinxtra
      • Verse Technology
    • Weather
      • Weather Plugins
      • Ambient Weather
    • Tools
      • Gambit Communications
      • PubNub
  • 📊Dashboards & Widgets
    • HTML Canvas
      • 3rd party packages
      • Preload Dashboard data
      • Built-in library
        • Properties
        • Methods
        • Listening events
        • API
      • Examples
        • Basics
        • Create an LCD screen with the HTML Canvas
        • Interacting with dashboard data
        • Change header's custom style
        • Adding real time using Socket.IO
        • Delete Variable data from a Device
        • Delete Variable data from Groups or Types of Devices
        • Navigation through Dashboard
        • Using a React library
      • Code editor
        • HTML Tab
        • CSS Tab
        • JavaScript Tab
    • Custom UI
      • Paragraph
      • Input combo
        • Text
        • Numeric
        • Numeric with buttons
        • Date
        • Time
        • Toggle
        • Dropdown
        • Multiple selection dropdown
      • Button
    • Custom Style
      • Dashboards
      • Widgets
    • Line chart
    • Pages
      • Getting started
      • Development
      • API
        • Page creation
        • Publish
  • 🤖UbiFunctions
    • Getting Started
      • Creating an UbiFunction
      • Coding an UbiFunction
      • Testing an UbiFunction
      • Authentication
      • Execution Time
      • Logs
    • Runtimes
      • Python
      • NodeJS
      • Custom Runtimes
    • Invocation
      • Time-based Trigger
      • HTTPS
      • MQTT Publish
      • Ubidots Event
    • Advanced
      • Account Token
      • Execution time
      • Raw Functions
      • CORS Policy
      • Async Execution
      • DaaS (Decoder as a Service)
      • Developing and Managing UbiFunctions with Ubidots CLI
    • Examples
    • Specs and Limits
    • Storage
      • File Storage API
      • Mutiple files
  • 🧩Plugins
    • What is a plugin?
    • Public vs. Private
    • Public plugins
      • Cron
      • Webhook
    • Private Plugins
      • Cron
      • Webhook
      • Widget
      • Device
    • Plugins development
      • Getting started
      • Cron
      • Webhook
      • Widget
      • Device
      • view.xml
      • view_widget.xml
    • Plugins deployment
      • Cron and Webhook
      • Widget
      • Device
    • Using the plugins
      • Cron and Webhook
      • Widget
      • Device
  • 📈SYNTHETIC VARIABLES
    • Getting started
      • Creating synthetic variables
      • Synthetic Variables' editor
    • Expressions
      • Mathematical
      • Date range
      • Rolling
      • Special functions
    • Specs and limits
    • Examples
      • Mathematical
      • Date range
      • Rolling
      • Special functions
  • ⌨️Developer tools
    • Javascript SDK
      • Overview
      • Getting started
      • Ubidots class
        • Get methods
        • Filter methods
        • Ubidots objects
          • Entity object
          • Paginator
      • Examples
    • CLI
      • Overview
      • Installing
      • Usage
      • SDK for UbiFunctions
  • 🏗️Apps
    • App builder
      • Custom sidebar
Powered by GitBook
On this page

Was this helpful?

Export as PDF
  1. Dashboards & Widgets
  2. HTML Canvas
  3. Examples

Create an LCD screen with the HTML Canvas

This example shows how to create an LCD screen on a dashboard by using the HTML Canvas widget.

HTML:

<div id="image_background">
<p>Last value:</p>
<span id="image_background_text">No data</span>
</div>

CSS:

@import url('https://fonts.googleapis.com/css?family=VT323');

#image_background {
background: url('https://i.imgur.com/uuYygjz.png') 0 / contain no-repeat;
font-family: "VT323";
font-size: 25px;
letter-spacing: 10.5px;
height: 220px;
width: 450px;
}

#image_background p, #image_background_text {
margin: 0;
left: 75px;
position: absolute;
}

#image_background p {
top: 88px;
font-size: 25px !important;
}

#image_background_text {
top: 121px;
}

JavaScript:

In the following code, the VAR_ID variable must be set according to the variable that should be displayed:

var bg = document.getElementById("image_background");
var text = document.getElementById("image_background_text");
var lastValue = null;
var TOKEN = ubidots.token;
var VAR_ID = "variable-id";

setInterval(function () { getLastValue(VAR_ID, TOKEN); }, 2000);

function makeHttpRequest(method, url, headers, payload) {
  return new Promise(function (resolve, reject) {
    var options = {
      method: method,
      headers: headers,
    };

    if (payload) {
      options.body = JSON.stringify(payload);
    }

    fetch(url, options)
      .then(function (response) {
        if (!response.ok) {
          throw new Error(response.statusText);
        }
        return response.json();
      })
      .then(function (data) {
        resolve(data);
      })
      .catch(function (error) {
        reject(error);
      });
  });
}

function changeImage(value) {
  var choose = "normal";
  var background = {
    blue: "https://i.imgur.com/ZE0W7Yx.png",
    normal: "https://i.imgur.com/uuYygjz.png",
    yellow: "https://i.imgur.com/RHvDkUE.png",
  };
  if (value <= 30) {
    choose = "blue";
    bg.style.color = "white";
  } else if (value > 30 && value <= 70) {
    choose = "yellow";
    bg.style.color = "white";
  }
  bg.style.background = "url(" + background[choose] + ") 0 / contain no-repeat";
}

function getLastValue(variableId, token) {
  var url =
    "https://industrial.api.ubidots.com/api/v1.6/variables/" +
    variableId +
    "/values";
  var headers = {
    "X-Auth-Token": token,
    "Content-Type": "application/json",
  };

  makeHttpRequest("GET", url + "?page_size=1", headers)
    .then(function (res) {
      if (lastValue === null || res.results[0].value !== lastValue) {
        text.textContent = res.results[0].value;
        lastValue = res.results[0].value;
        changeImage(lastValue);
      }
    })
    .catch(function (error) {
      console.error(error);
    });
}

Once the settings are saved, it will look like this:

Adjusting the screen's contrast

Modify the HTML to:

<div id="image_background">

<img id="display_background" src="https://i.imgur.com/meoKhMG.png" />

<p>Last value:</p>
<span id="image_background_text">No data</span>
</div>

Modify the CSS code to:

@import url('https://fonts.googleapis.com/css?family=VT323');

#image_background {
background: url('https://i.imgur.com/ehNdUxY.png') 0 / contain no-repeat;
font-family: "VT323";
font-size: 25px;
letter-spacing: 10.5px;
height: 220px;
width: 450px;
}

#image_background p, #image_background_text {
margin: 0;
left: 75px;
position: absolute;
}

#image_background p {
top: 88px;
font-size: 25px !important;
}

#image_background_text {
top: 121px;
}

#display_background {
height: 94px;
position: absolute;
top: 70px;
left: 52px;
pointer-events: none;
}

Modify the JavaScript code to:

var bg = document.getElementById("display_background");
var text = document.getElementById("image_background_text");
var lastValue = null;
var lastContrast = null;
var TOKEN = ubidots.token;
var VAR_ID_LV = "id-of-variable-to-be-displayed";
var VAR_ID_CONTRAST = "id-of-contrast-variable";
var scale = d3.scaleLinear().range([0, 4]).domain([0, 1023]);


setInterval(function () {
    // Get LCD Screen last value
    getLastValue(VAR_ID_LV, TOKEN, function (res) {
      var value = null;
      try {
        value = res.results[0].value;
      } catch (e) {
        console.log("No data");
      }
      if (
        (lastValue === null || value !== lastValue) &&
        value !== null
      ) {
        text.textContent = value;
        lastValue = value;
      }
    });

    // Get LCD Screen contrast
    getLastValue(VAR_ID_CONTRAST, TOKEN, function (res) {
      var value = null;
      try {
        value = res.results[0].value;
      } catch (e) {
        console.log("No data");
      }
      if (
        (lastContrast === null || value !== lastContrast) &&
        value !== null
      ) {
        bg.style.filter = "contrast(" + scale(value) + ")";
        lastContrast = value;
      }
    });
  }, 2000);


function makeHttpRequest(method, url, headers, payload) {
  return new Promise(function (resolve, reject) {
    var options = {
      method: method,
      headers: headers,
    };

    if (payload) {
      options.body = JSON.stringify(payload);
    }

    fetch(url, options)
      .then(function (response) {
        if (!response.ok) {
          throw new Error(response.statusText);
        }
        return response.json();
      })
      .then(function (data) {
        resolve(data);
      })
      .catch(function (error) {
        reject(error);
      });
  });
}

function getLastValue(variableId, token, cb) {
  var url =
    "https://industrial.api.ubidots.com/api/v1.6/variables/" +
    variableId +
    "/values";
  var headers = {
    "X-Auth-Token": token,
    "Content-Type": "application/json",
  };

  makeHttpRequest("GET", url + "?page_size=1", headers)
    .then(function (res) {
      if (typeof cb === "function") cb(res);
    })
    .catch(function (error) {
      console.error(error);
    });
}

Lastly, add another 3rd party library needed for this implementation:

https://cdnjs.cloudflare.com/ajax/libs/d3/4.9.0/d3.min.js

This is the result:

PreviousBasicsNextInteracting with dashboard data

Last updated 1 year ago

Was this helpful?

📊