简体   繁体   中英

Darken the color of svg element each time on button click using D3 V3 or JavaScript

I have a D3 graph consisting of various Nodes/Links. In this i have a functionality in which when i click on node and then click on a button it reduces the opacity of every other element except the intermediate connected nodes and links and also changes of link to Blue to show the circuit.

样本图片

What I want to achieve is when multiple such nodes are selected one after one, the link which are common with any previous circuit, it should change it's blue color to one shade darker.

I do not want to do this using increasing opacity, I want to change to color to be one shade darker than previous.

I have made the logic to find common links in circuit but using D3/JS, how to increase color code to a darker tone each time for any svg element on button click.

For example: In the code given below I want to achieve a darker tone of blue each time on button click, instead of changing it to red.

 d3.select('#toDO').on('click', function() { d3.select("#PathID").attr("stroke" , "red") }) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> <svg height="210" width="400"> <path id="PathID" d="M150 0 L75 200" stroke="blue"/> </svg> <button id="toDO">Click</button> 

D3 has a very convenient method named darker(k) , which, as the name implies:

Returns a darker copy of this color. If k is specified, it controls how much darker the returned color should be. If k is not specified, it defaults to 1. The behavior of this method is dependent on the implementing color space.

So, in your code, you just need to use d3.color (D3 v4 or v5):

d3.color(d3.select("#PathID").attr("stroke")).darker()

Or d3.rgb (D3 v3):

d3.rgb(d3.select("#PathID").attr("stroke")).darker()

Here is the demo:

 d3.select('#toDO').on('click', function() { d3.select("#PathID").attr("stroke", d3.rgb(d3.select("#PathID").attr("stroke")).darker()) }) 
 <script src="https://d3js.org/d3.v3.min.js"></script> <button id="toDO">Click</button> <br> <svg height="210" width="400"> <path id="PathID" d="M150 0 L75 200" stroke="blue" stroke-width="10px"/> </svg> 

If you click the button several times, the stroke will be almost black.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM