Changing the shading of an arc in d3.js: Tips and tricks

I've been attempting to create a gauge with a needle that changes the background color of the ring for the past few days.

My goal is to dynamically update the colors of an arc within a gauge I developed in d3.js

This is my current gauge setup with the arc:

var randomConfigObject = {
    size: 200,
    clipWidth: 200,
    clipHeight: 110,
    ringInset: 20,
    ringWidth: 20,

    pointerWidth: 10,
    pointerTailLength: 5,
    pointerHeadLengthPercent: 0.9,

    minValue: 0,
    maxValue: 10,

    minAngle: -90 - 45,
    maxAngle: 90 + 45,

    transitionMs: 750,

    majorTicks: 5,
    labelFormat: d3.format(',g'),
    labelInset: 10,

    arcColorFn: d3.interpolateHsl(d3.rgb('#e8e2ca'), d3.rgb('#3e6c0a'))
};

// more code here...


if ( !window.isLoaded ) {
    window.addEventListener("load", function() {
        onDocumentReady();

        // Very dodge way of doing this!
        document.getElementById('pointer').append(document.getElementById('plane'));
    }, false);
} else {
    onDocumentReady();
}
// CSS styles go here...
<script type="text/javascript" src="http://d3js.org/d3.v2.min.js"></script>
<script src="http://bernii.github.io/gauge.js/dist/gauge.min.js"></script>
<div id="power-gauge"></div>
<br>
<svg width="1200" height="600" viewBox="0 0 900 350">
<g id="plane" style="" transform="translate(-55) scale(0.15, 0.15) rotate(-45 100 100)">
<defs id="defs0"></defs>
<path id="planepath" d="M 439.48098,95.969555 L 393.34268,142.46481 L ... fill-opacity:1;fill-rule:nonzero;stroke:none;marker:none;visibility:visible;display:inline;overflow:visible" id="path1"></path>
</g>
</svg>

I want to achieve the same effect as this example but with a moving needle and changing arc color:

Any help would be appreciated. Thank you.

Answer №1

After following the guidance provided by @Florian, I successfully added a second arc layer that updates dynamically with data.

I have included the code snippet in this post for anyone who may find it helpful.

var randomConfigObject = {
    // Configuration Object
};

// Function to create subarcs
function subarcCreator(newArc, innerRadius, outerRadius, start, end) {
    // Code here
}

// Plane string image data
var planeStringImage = "M 439.48098,95.969555 L ... ";

// Styling for plane element
var planeStyleElement = "opacity:1;color:#000000;fill:#000000;...";

// Data labels for ticks on gauge
var tickDataLabel = ['S', '210', '240', ...];

// Gauge function definition
var gauge = function(container, configuration, config) {
    // Implementation details
};

// Callback when document is loaded
function onDocumentReady() {
    // Implementation code
}

// Check if document is loaded before calling onDocumentReady
if (!window.isLoaded) {
    window.addEventListener("load", function() {
        onDocumentReady();
        // Append plane element inside pointer element
        document.getElementById('pointer').append(document.getElementById('plane'));
    }, false);
} else {
    onDocumentReady();
}
// CSS styling for gauge visualization
body {
    font-family: Helvetica, Arial, sans-serif;
    margin: 32px;
}

#power-gauge g.arc {
    fill: steelblue;
}

#power-gauge g.pointer {
    fill: #3ed850;
    stroke: #32ad40;
}

// More CSS styles...

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

Executing Java Script on several identical elements

Currently, I am facing an issue with my JavaScript function that is supposed to toggle the display of titles within elements. The function works perfectly fine on the first element, but it does not work on the other elements. Here is the code snippet: ...

Hey there, I'm looking to automatically delete new users from my mongoDB atlas database if they haven't verified their phone number within 2 minutes. I believe using the TTL feature would be

Database Schema In my User schema, the field isVerified is initially saved as false. The user enters their phone number, receives a verification token via SMS, and both the token and number are saved in the database. Once the user enters the verification ...

Issue with mouse movement in Selenium and Protractor not functioning as expected

Greetings! I am currently facing an issue in my Angular application with Openlayers3 map integration. There is a layer representing a building on the map, and when I try to click on a building during testing, it should trigger a side panel displaying image ...

"Error: The function $(...).autocomplete is not recognized" in conjunction with Oracle Apex

Currently experiencing some frustration trying to solve the issue at hand. The Uncaught TypeError: $(...).autocomplete is not a function error keeps popping up and I have exhausted all resources on Stack Overflow in an attempt to fix it. This problem is oc ...

Transforming a JavaScript variable into a PHP variable

Is there a way to convert a JavaScript variable obtained from videoel.getCurrentTime function into a PHP variable, so that it can be included in an SQL Insert Query like INSERT INTO tblData VALUES ('$phpVarFromJavascript')? ...

Setting the default dropdown option in Angular

For my latest question, I decided to utilize ng-init. However, upon loading the page, I noticed that there is a blank default option. When I click and select another option, the blank option disappears. How can I remove this initial blank option? Here is ...

What is the best way to specify a type for an object without altering its underlying implicit type?

Suppose we have a scenario where an interface/type is defined as follows: interface ITest { abc: string[] } and then it is assigned to an object like this: const obj: ITest = { abc: ["x", "y", "z"] } We then attempt to create a type based on the valu ...

What is the distinction between declaring a variable as var $a=$() versus var a?

In some cases, in JQuery we assign a variable like var $a=$(), resembling the declaration of a function. I am curious to know if there is any difference if we simply define the variable as var a? ...

What could be the reason for XMLHttpRequest's readystate being something other than 4?

Currently delving into the realm of AJAX for the first time, and endeavoring to construct a basic application that computes the required grade on a final exam based on past assessment results. The user keys in their grades into the form, subsequent to whi ...

Regular expressions should be utilized in a way that they do not match exactly with a

Can someone help me create a regular expression for an html5 input pattern attribute that excludes specific items? How can I convert ab aba ba into a pattern that will match anything that is not exactly one of these words? For example, I want the fol ...

Combining objects using mathematical operations for identical properties in JavaScript

Imagine I have two sets of data: const obj1 = { CRITICAL: 0, ERROR: 1, INFO: 0, WARNING: 0, }; const obj2 = { CRITICAL: 0, ERROR: 0, INFO: 0, WARNING: 1, }; I'm looking to merge them into a single object with the summed values for e ...

Incorporating Chartist.JS with Jade-syntax pages

Hello everyone, I need some assistance with integrating Chartist.JS into a node Template to display a basic bar graph. The script doesn't seem to be working properly and I'm unsure of what's causing the issue. Can anyone please take a look a ...

The function will provide the value prior to the execution of the Jquery image loading

if (DataService.Validation(file)) { //angularjs call to api controller }; //DataService Validation: function (file) { var Url = URL.createObjectURL(file); var img = new Image(); $(img).load(function () { var imgwidth = this. ...

Which is better for cycling through a list of items: CSS or JavaScript?

Currently, I have a navigation bar set up as an unordered list (<ul>), but some list items are not visible. I want to implement functionality where clicking arrows will move the elements left or right by hiding or showing the leftmost or rightmost it ...

Integrating CSS with Material-UI in a React project: A step-by-step guide

I am currently developing a project using React (along with TypeScript) and the Material-UI library. One of my requirements is to implement an animated submit button, while replacing the default one provided by the library. After some research, I came acr ...

What is the best way to merge two similar arrays of objects into one array object?

Apologies in advance if this question has been asked previously, I'm struggling with how to phrase it. Essentially, the API I'm using is returning an array of similar objects: const response.survey = [ { 1: { id: 1, user: user_1, points: 5 ...

Using Javascript to access a website from a Windows Store application

Currently, I am working on a project to create a Windows store app using HTML and JavaScript. One of the key components of my app involves logging into a specific website with a username and password. Here is an example website for reference: The process ...

Unable to launch React Native project on emulator now

Something seems off with my App as it won't start up on my AS Emulator. Everything was running smoothly yesterday, but today it's not working - possibly due to me moving the npm and npm-cache folders, although they are configured correctly with n ...

Enhance the efficiency of synchronized horizontal scrolling using React/Redux to boost overall performance

I'm currently working on creating a grid with synchronized horizontal scrolling across different sections (such as a header and multiple table sections below). Each section should scroll together horizontally, maintaining synchronization using a redux ...

Enhabling Effortless Button Activation & Sustained Navigation State: Integrating Dynamic Navigation in React

"I am facing a React challenge and seeking assistance to implement a specific functionality with a button. At present, the button starts with a false state, but I intend for it to automatically activate and reveal a navigation component (nav) when the ...