Seeking assistance in the development of a visual depiction of device orientation through JS

My goal is to visually represent the device orientation values alpha, beta, and gamma by creating a series of "bars" for each value. Currently, I have managed to display only the values in plain text using innerHTML. However, I envision these bars moving in response to changes in the alpha, beta, and gamma values. Here's a rough sketch of what I'm aiming for: https://i.sstatic.net/m1Ubx.png

This is how my code looks at the moment:

<!DOCTYPE HTML>
<html>

  <body>
    <p>Alpha: <span id="alpha"></span></p>
    <p>Beta: <span id="beta"></span></p>
    <p>Gamma: <span id="gamma"></span></p>

    <canvas id="myCanvas" width="400" height="400"></canvas>
    <script>
      // Listen for device orientation event
      window.ondeviceorientation = function(eventData)
      {
        // Show alpha, beta and gamma values
        document.getElementById('alpha').innerHTML = Math.round(eventData.alpha);
        document.getElementById('beta').innerHTML = Math.round(eventData.beta);
        document.getElementById('gamma').innerHTML = Math.round(eventData.gamma);
      }
    </script>
  </body>
</html>

I wonder if CSS styling or utilizing the canvas element could help achieve this dynamic visual representation. While initializing the canvas with ondeviceorientation poses a challenge, any guidance on implementing this feature would be greatly appreciated.

Answer №1

To create this effect, there's no need for a canvas. You can achieve it by adjusting the width of your spans and using CSS to define the colors.

Make sure your spans have either display: inline-block or display: block set in their CSS properties; otherwise, changing the width won't have any effect. Alternatively, you can use div elements instead of spans. Also, set a height property like 30px.

You can then use CSS or inline styles to specify the background-color for alpha, beta, and gamma. After that, adjust the width using the Element.style.width property (in pixels) based on the device orientation with JavaScript.

Consider the purpose of the bar sizes and their behavior carefully. The design decisions are up to you, so I won't delve deeply into explaining how the code works. Essentially, the bars are sized relative to the value range. Each alpha, beta, and gamma value is converted into a percentage of its total range and multiplied by the maximum width specified for the bars.

The ranges I used were obtained from here: https://developer.mozilla.org/en-US/docs/Web/API/Detecting_device_orientation

The formula for calculating the bar width when values are in the range [a, b], the maximum bar width is max_w, and the alpha, beta, or gamma value is value, is as follows:

width = max_w * ((-a + value) / (b - a))

Remember to include "px" at the end.

// Listen for device orientation event
window.ondeviceorientation = function(eventData)
{
  let maxWidth = 200;
  // Show alpha, beta and gamma values
  document.getElementById('alpha').style.width = Math.round(maxWidth * eventData.alpha / 360) + "px";
  
  document.getElementById('beta').style.width = Math.round(maxWidth * (180 + eventData.beta) / 360) + "px";
  document.getElementById('gamma').style.width = Math.round(maxWidth * (90 + eventData.gamma) / 180) + "px";
}
p span{
  height : 30px;
  display : inline-block;
}

#alpha{
  background-color : green;
}

#beta { 
  background-color : yellow;
}

#gamma {
  background-color : purple
}
<p> Alpha: <span id="alpha"> </span> </p>
<p> Beta: <span id="beta"> </span> </p>
<p> Gamma: <span id="gamma"> </span></p>

Answer №2

In response to Khauri McClain's suggestion for a static representation of orientation values, if you are looking to animate them (possibly using canvas), you can achieve this effect with CSS keyframes. Below is a simple example.

html,
body {
  height: 100%;
}

body {
  background-color: #f5f7f9;
  color: #6c6c6c;
  margin: 0;
  position: relative;
}

.container {
  width: 30em;
  margin: 2em;
}

.label {
  float: left;
  width: 5em;
  height: 2em;
}

.orientation {
  float: right;
  background-color: #e5e9eb;
  height: 2em;
  position: relative;
  width: 24em;
}

.alpha {
  animation-duration: 3s;
  animation-name: alpha-anim;
  animation-fill-mode: forwards;
  background-color: #ff2d55;
  height: 100%;
  position: relative;
}

.beta {
  animation-duration: 3s;
  animation-name: beta-anim;
  animation-fill-mode: forwards;
  background-color: #4cd964;
  height: 100%;
  position: relative;
}

.gamma {
  animation-duration: 3s;
  animation-name: gamma-anim;
  animation-fill-mode: forwards;
  background-color: #007aff;
  height: 100%;
  position: relative;
}

@keyframes alpha-anim {
  0% {
    width: 0;
  }
  100% {
    width: 14em;
  }
}

@keyframes beta-anim {
  0% {
    width: 0;
  }
  100% {
    width: 3em;
  }
}

@keyframes gamma-anim {
  0% {
    width: 0;
  }
  100% {
    width: 20em;
  }
}
<div class="container">
  <div class="label">Alpha:</div>
  <div class="orientation">
    <div class="alpha"></div>
  </div>
</div>

<div class="container">
  <div class="label">Beta:</div>
  <div class="orientation">
    <div class="beta"></div>
  </div>
</div>

<div class="container">
  <div class="label">Gamma:</div>
  <div class="orientation">
    <div class="gamma"></div>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Hover over CSS sprite

My anchor tag looks like this: <a href="#"> <i class="ico01"></i> <span>Text</span> </a> The ico01 class applies an image using CSS sprite. I want to change the background color of the entire content inside the a ...

"RecognitionAudio variable missing" and "InactiveRpcError occurred" [Utilizing the Google text-to-speech API]

I have a goal I'd like to achieve. A user communicates with a web browser. The web browser records the user's voice as a WAV file using Recorder.js and sends it to a server running on Google App Engine Standard environment with Python 3.7. The ...

Troubleshooting issue with jQuery animate not correctly scrolling

I am experiencing an issue with my jQuery code that is supposed to scroll a smaller container element within a larger container element when a button is clicked. Despite testing with an alert and verifying that the code is working, the scrolling functional ...

What is the correct method to authenticate a user's ID token in Firestore with Javascript?

I am in the process of developing a react native application and have integrated Firebase, specifically firestore, for data management purposes. My current goal is to incorporate an automatic login feature in my app, where users remain signed in even after ...

Javascript time intervals run rapidly during tab changes

I am facing an issue where my neck is constrained at regular time intervals. I have a function that helps me calculate time one second at a time: Header.prototype= { time_changed : function(time){ var that = this; var clock_handle; ...

What are some effective methods for preventing CodeMirror from appearing as a blank white box upon initialization?

In my project with Codemirror version 5.62.3 and the 'monokai' theme set to a dark background, I am facing an issue where upon reloading the page, the CodeMirror initializes as a small white box before the proper styling is applied. I have attemp ...

The cropper fails to load within the image element inside a modal pop-up

Utilizing fengyuanchen's cropper library, I am cropping an uploaded image and then submitting it to a form. <div id="change-dp" uk-modal> <div class="uk-modal-dialog uk-modal-body"> <button class="uk ...

Browsing through items within arrays to evaluate their values

I am facing an issue with two arrays that consist of objects. The first array contains restaurant objects with attributes such as name and averagePrice, while the second array has price objects (cheap, medium, expensive) with properties like label, lowEnd, ...

Is the "Illegal invocation" error popping up when using the POST method in AJAX?

Is there a way to retrieve JSON data using the POST method in Ajax? I attempted to use the code below but encountered an error: TypeError: Illegal invocation By following the link above, I was able to access JSON-formatted data. However, please note th ...

Unexpected results: jQuery getJSON function failing to deliver a response

I am facing an issue with the following code snippet: $.getJSON('data.json', function (data) { console.log(data); }); The content of the data.json file is as follows: { "Sameer": { "Phone": "0123456789", }, "Mona": { "Phone": ...

The process of extracting text from an HTML element using Selenium and Node.js

After searching extensively on stackoverflow, I came up empty-handed in finding a solution to my problem. Can anyone lend a hand? I am trying to extract the text from an HTML element using the following code: var element = driver.findElement(webdriver.By ...

Achieving the ideal HTML layout for small screens that differs from larger screens is a common challenge faced by web developers

After implementing the markup code, I achieved the desired layout on large screens. However, when reducing the screen size to a phone level, I require a layout similar to image-3, and on larger screens like laptops, it should resemble image-1. Image-1 and ...

What is causing the qtip tooltip to show up on buttons with different ids?

I have a requirement to display tooltips only for specific buttons and not for others. I am facing an issue where the tooltip intended for the TAB button is showing up when hovering over other buttons like FOO and BAR as well. Could this be due to them sha ...

Styling React components using class names

Struggling with implementing a sidebar feature using the guidance provided in this example. However, I am facing difficulty in applying the necessary styles to each className... Here's what I've attempted so far, but unfortunately, no styles see ...

Is it advisable to utilize media queries and transform: translateY(-%) to position content above the mobile keyboard?

I've been struggling for nearly a whole day and could really use some assistance. I'm having trouble understanding how chat web apps manage to work around this particular issue. There have been numerous forum posts discussing the problem: I am tr ...

What is the best way to pass a mask without using a plug-in when dealing with an input value in Vue.js?

As someone who has previously implemented the function using pure JavaScript, I am now faced with the challenge of incorporating it into vue.js and determining which lifecycle hooks are best suited for this task. This issue arises as I am a beginner prepar ...

Is there a way to set the size of my unique carousel design?

Having some trouble with my modal image carousel; the dimensions keep shifting for different image sizes. Image 1 Image 2 ...

Automatically toggle Bootstrap checkbox switch to OFF upon successful completion of AJAX script

On my Employee screen, I have an HTML Form with a Bootstrap Checkbox Switch that toggles the visibility of password change fields. Clicking it reveals or hides the fields accordingly. I'd like to set this switch to "off" when the AJAX script updates ...

Loop through an HTML table in order to emphasize variations in cells that contain multiple comparison items

I am interested in highlighting variances between the initial row of a table and all other rows based on columns. I have successfully managed to achieve this when each cell contains only one item/comparison. However, I would like to expand this to include ...

Is there a way to verify in AngularJS whether ng-model contains a string or a numerical value?

In my Angular application, I have written a JavaScript function that checks if the value of a text field is undefined or empty, and it is working properly. $scope.checkNumber = function(user_answer){ if(user_answer == undefined){ return false; } } My ...