information directed towards particular positions on a meter

I am in the process of creating a dashboard skin that receives data from a game via a plugin. I have encountered a problem with the RPM gauge. The issue is that the angle from 0 to 5 on the gauge is smaller than the angle from 5 to 10. I am attempting to set the angle for 5 to a specific value. The minimum angle is -125 and the maximum angle is 125, so 0 = -125, 5 = -90, but 10 = -40. This means the angle from 0 to 5 is 35 degrees, while from 5 to 10 it is 50 degrees. I only have HTML code and CSS for the gauge needle placement.

HTML:

<div class="truck-engineRpm gauges" data-type="meter" data-min="0" data-max="25" data-min-angle="-125" data-max-angle="90"></div>

CSS:

.truck-engineRpm {
    z-index: 1;
    visibility: visible;
    position: absolute;
    left: 1816px;
    top: 391px;
    width: 40px;
    height: 391px;
    background-image: url("images/needle.png");
    transform: rotate(-125deg);
    transform-origin: 50% 322px;
    transition: 300ms linear;
}

There is a discrepancy in the degrees between the points on the gauge I created, as it is linear, while the gauge in question is not. When assigning a value to the gauge using JavaScript, it does not align with the data on the gauge.

I aim to develop a non-linear gauge with fixed angle settings. Currently, I only have a linear gauge with minimum/maximum data and angles.

---- Issue Resolved ----

I determined the value at which the needle was pointing (e.g., when it was on 5, the data was 350 rpm), and calculated how to display the game RPMs correctly.

JavaScript code:

var Rpm = data.truck.engineRpm;
var RpmCalc = data.truck.engineRpm;
var RpmRange1 = data.truck.engineRpm;
var RpmRange2 = data.truck.engineRpm - 500;
var RpmRange3 = data.truck.engineRpm - 1000;
var RpmRange4 = data.truck.engineRpm - 1442;
var RpmRange5 = data.truck.engineRpm - 1500;
var RpmRange6 = data.truck.engineRpm - 2000;
if (Rpm >= 0 && Rpm <= 500) {
    data.engineRpm = RpmCalc - (0.3 * RpmRange1);
} else if (Rpm > 500 && Rpm <= 1000) {
    data.engineRpm = RpmCalc - (0.01 * RpmRange2 + 150);
} else if (Rpm > 1000 && Rpm <= 1442) {
    data.engineRpm = RpmCalc + (0.35 * RpmRange3 - 155);
} else if (Rpm > 1442 && Rpm <= 1500) {
    data.engineRpm = RpmCalc + (0.38 * RpmRange4);
} else if (Rpm > 1500 && Rpm <= 2000) {
    data.engineRpm = RpmCalc + (0.08 * RpmRange5 + 22);
} else if (Rpm > 2000 && Rpm <= 2500) {
    data.engineRpm = RpmCalc - (0.124 * RpmRange6 - 62);
}

This solution may not look elegant, but if it works, it works :)

Answer №1

Allow me to demonstrate a simple concept through an example. By mapping numerical units within a specified range to corresponding numbers, we create a straightforward and effective method.

"use strict";
window.addEventListener('load', onLoaded, false);

let gaugeMap = [];

function onLoaded(evt) {
  let canvas = document.querySelector('canvas');
  canvas.style.backgroundImage = `url(${imgSrc})`;

  gaugeMap.push(new gaugeRange(0, 500, 214, 180));
  gaugeMap.push(new gaugeRange(500, 1000, 180, 130));
  gaugeMap.push(new gaugeRange(1000, 1500, 130, 64.5));
  gaugeMap.push(new gaugeRange(1500, 2000, 64.5, 9));
  gaugeMap.push(new gaugeRange(2000, 2500, 9, -34));

  document.querySelector('input').addEventListener('input', onRpmSliderChange, false);
  onRpmSliderChange.apply(document.querySelector('input'), null);
}

function onRpmSliderChange(evt) {
  let rpm = this.value;

  document.querySelector('#rpmOut').textContent = rpm;

  gaugeMap.forEach(function(range) {
    if (range.contains(rpm))
      drawNeedle(range.map(rpm));
  });
}

function drawNeedle(angleDeg) {
  const needleLen = 52;

  let canvas = document.querySelector('canvas');
  let context = canvas.getContext('2d');
  let width = canvas.width,
    height = canvas.height;
  context.clearRect(0, 0, width, height);

  context.beginPath();
  context.lineWidth = 2;
  context.strokeStyle = 'white';
  context.moveTo(width / 2, height / 2);

  let dx = Math.cos(angleDeg * 3.141 / 180.0) * needleLen;
  let dy = Math.sin(angleDeg * 3.141 / 180.0) * needleLen;

  context.lineTo(width / 2 + dx, height / 2 - dy);
  context.stroke();
  context.closePath();
}

class gaugeRange {
  constructor(rpm1, rpm2, angle1, angle2) {
    if (rpm1 <= rpm2) {
      this.rpm1 = rpm1;
      this.rpm2 = rpm2;
      this.angle1 = angle1;
      this.angle2 = angle2;
    } else {
      this.rpm2 = rpm1;
      this.rpm1 = rpm2;
      this.angle2 = angle1;
      this.angle1 = angle2;
    }
  }
  contains(rpm) {
    if (rpm >= this.rpm1 && rpm <= this.rpm2)
      return true;
  }

  map(rpm) {
    if (this.contains(rpm) == false)
      return false;
    let proportion = (rpm - this.rpm1) / (this.rpm2 - this.rpm1);
    let deltaAngle = this.angle2 - this.angle1;
    let value = (proportion * deltaAngle) + this.angle1;
    return value;
  }
}

var imgSrc = 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wI ...';
<canvas width='128' height='128'></canvas><br>
<div style='display:inline-block; text-align: center'>
  <input type=range min=0 max=2500 value=0 id='rpmSlider' /><br>
  <span id='rpmOut'></span>
</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

Error: Cannot iterate over Redux props map as it is not a function

I've encountered an issue while trying to render out a Redux state by mapping through an array of objects. Despite receiving the props successfully, I keep getting an error stating that 'map is not a function'. It seems like the mapping func ...

How can I use jQuery to set up form validation for an input textfield?

Check out this code snippet: <form data-test="loginForm-container" novalidate="" method="POST" enctype="multipart/form-data"> <div class="css-o5d3v1 e1ovefus2"> <div data-test="guestForm-email-wrapper" class="e1ovefus1 css-yjv4po e1eu3s ...

Fullcalendar feature that restricts users from selecting multiple days for an event

I am using the fullcalendar plugin from http://fullcalendar.io/ and I want to restrict users from creating events spanning multiple days. $('#calendar').fullCalendar({ defaultView: 'agendaWeek', lang: "fr", header: ...

Retrieve the element that is currently being hovered over within the same nested selector

I am facing a challenge in selecting the currently hovered element with a nested selector. The ".frmElement" class is used as the selector. When I hover over the ".frmElement" element at a certain level, all the previous selector elements display the hover ...

ReactForms Deprication for NgModel

According to Angular, certain directives and features are considered deprecated and could potentially be removed in upcoming versions. In a hypothetical scenario, let's say I am using NgModel with reactive forms, which Angular has marked as deprecate ...

Add unique content to a div upon page reload

Whenever the page is refreshed, I would like to add a random anchor from an array into a specific div. Here's my current code: <div id="exit-offer" class="exit-offer-dialog"> <div class="offer-content" id="banner-load"> <bu ...

Next.js Static Paths Filtering

How can I retrieve only filtered paths from getStaticPaths? This function currently returns all posts export async function getStaticPaths() { const { data } = await axios.get(`${url}/category`, config); const paths = data.map((post) => { ...

Tips for monitoring input content "live"

Currently, I am in the process of developing a web form that includes a text field intended to receive numeric values. If the user enters non-numeric characters into this field, the form will not submit. However, there is no error message displayed to noti ...

Revamp the Bootstrap Carousel Control by replacing the default navigation arrows with stylish arrows featuring circle backgrounds

Looking to update the appearance of the carousel icons in Bootstrap 4? How about changing them from simple arrows to arrows with dark semi-opaque circles underneath? If you're wondering how to achieve this modification, keep in mind that the icons ar ...

Determine the number of distinct elements in fields using MongoDB aggregation

After executing my query, I received documents in the following format: { _id: '48nmqsyxmswpkkded2ac_331fabf34fcd3935', actions: { sales: { pixel: [Object] } }, date: Sun Jul 27 2014 00:00:00 GMT-0400 (EDT), client: '48nmqsyxmswpkkded ...

Breaking down an Express app into modules: incorporating a function, a class, and req.pipe

Below are two servers and two gqlServers, each with different functionalities. All combinations of them work. The task at hand is to enhance express with predefined code patterns that can be shared across various apps through additional methods. What com ...

Create a box with borders and divisions using HTML

Hello, I am trying to create a box in HTML with a slanted divider line inside. How can I achieve this design? I am aiming to replicate the layout shown in this image: Link to Image I have tried implementing the code below, but the alignment is not matchi ...

Utilize the JavaScript Email Error Box on different components

On my website, I have implemented a login system using LocalStorage and would like to incorporate an error message feature for incorrect entries. Since I already have assistance for handling email errors on another page, I am interested in applying that sa ...

Struggling with implementing responsive mobile buttons that stack in a column? Here's the solution

My content is nearly responsive on all screen sizes, but I'm having trouble getting the buttons to stack neatly in a column. Can anyone provide suggestions on how to fix this issue? You can view the current progress below. Thank you in advance for any ...

Is there a way for me to figure out if a Primefaces RadioCheckbox has been selected?

Despite the numerous examples available on how to count checked checkboxes, I am facing difficulties in getting it to work. My goal is to enable a button when at least one checkbox is checked on the page, and disable it when none are selected. However, n ...

Enhance the Error class in Typescript

I have been attempting to create a custom error using my "CustomError" class to be displayed in the console instead of the generic "Error", without any success: class CustomError extends Error { constructor(message: string) { super(`Lorem "${me ...

Angular: merging multiple Subscriptions into one

My goal is to fulfill multiple requests and consolidate the outcomes. I maintain a list of outfits which may include IDs of clothing items. Upon loading the page, I aim to retrieve the clothes from a server using these IDs, resulting in an observable for e ...

Kurento's WebRTC feature is currently experiencing difficulties with recording functionality

Currently, I am attempting to capture video using the Kurento Media Server with nodejs. Following the hello-world example provided here, I connected a recorderEndpoint to the webrtcEndpoint and successfully got everything up and running. However, on the se ...

Accessing data from a CD-ROM or DVD through a web browser

I am currently working on developing a web application for a friend that will enable users to simply click a button to upload all the content from the CD-ROM or DVD they have inserted directly to a server. It's not feasible to rely on the standard br ...

What is the best way to determine when all asynchronous tasks and callbacks have been completed so that we can proceed securely?

Here is a code snippet that reads a file containing documents sorted by categories and values in descending order. It then modifies the documents with the highest value for each category. Below is the code: var MongoClient = require('mongodb'). ...