Retrieving and updating the attribute value for d3.symbolTriangle

Currently, I am utilizing d3.symbolTriangle to create equilateral triangles in my project. I am interested in learning how to access and modify the attribute values.

This is a snippet of my code:

var body = d3.select("body");
var triangle = d3.symbol()
   .type(d3.symbolTriangle);
Group = [];

var svg = body.append("svg")
  .attr("width", width)
  .attr("height", height)
  .style("border", "1px solid black")
  .on("mousemove", function() {
    mouse = d3.mouse(this);
    isMouseMoving=true;
  });

function drawTriangles(number) {
  for (var i = 0; i < number; i++) {
    Group[i] = svg.append("g")
        .attr("id",i);
    var dim = Math.floor(Math.random() * 800 + 50);
    var r = Math.random()*360;
    Group[i].append("path")
      .attr("d", triangle.size(dim))
      .attr("transform", function (d) {
        var boundingBox = this.getBBox();
        var elementWidth = Math.ceil(boundingBox.width);
        var randomXOffset = Math.random() * (width - elementWidth - 2 * borderSize) + elementWidth/2 + borderSize;
        var randomYOffset = Math.random() * (height - elementWidth - 2 * borderSize) + elementWidth/2 + borderSize;
            return "translate(" + randomXOffset + "," + randomYOffset + ")rotate("+r+")";
        })
      .attr("fill", "rgb(" + parseInt(Math.random() * 255) + "," + parseInt(Math.random() * 255) + "," + parseInt(Math.random() * 255) + ")")
      .attr("opacity", 2)
      .attr("stroke", "black")
      .attr("proof", "Hello")
      .attr("radius", function() {
        return Math.sqrt(dim/(Math.sqrt(3)*3));
      });
  }
}

If I wish to retrieve the values of translate (the position of the triangle) or radius, and then set new values, for instance during a transition, how can I accomplish this? I attempted the following approach:

Group[i]._groups[0][0].childNodes[0].attributes["radius"].nodeValue

However, I am doubtful if this is the correct method to achieve my goal.

Answer №1

Within D3, a function such as attr or style serves as both a setter and a getter. When provided with two arguments, it acts as a setter:

.attr("foo", bar);

However, when supplied with just one argument, it functions as a getter:

.attr("foo");

Considering the code snippet below...

<script src="https://d3js.org/d3.v4.min.js"></script>
 <body>
 <script>
    var width = window.innerWidth;
 var height = window.innerHeight;
 var number = 30;
 var body = d3.select("body");
 var triangle = d3.symbol()
    .type(d3.symbolTriangle);
var margins = 20;
var Group = [];
var borderSize = 10;

var svg = body.append("svg")
.attr("width", width)
.attr("height", height)
.style("border", "1px solid black");


 function drawTriangles(number) {
    for (var i = 0; i < number; i++) {
    Group[i] = svg.append("g")
        .attr("id",function(){ return "id" + i});
    var dim = Math.floor(Math.random() * 800 + 50);
    var r = Math.random()*360;
    Group[i].append("path")
      .attr("d", triangle.size(dim))
      .attr("transform", function (d) {
        var boundingBox = this.getBBox();
        var elementWidth = Math.ceil(boundingBox.width);
        var randomXOffset = Math.random() * (width - elementWidth - 2 * borderSize) + elementWidth/2 + borderSize;
        var randomYOffset = Math.random() * (height - elementWidth - 2 * borderSize) + elementWidth/2 + borderSize;
            return "translate(" + randomXOffset + "," + randomYOffset + ")rotate("+r+")";
        })
      .attr("fill", "rgb(" + parseInt(Math.random() * 255) + "," + parseInt(Math.random() * 255) + "," + parseInt(Math.random() * 255) + ")")
      .attr("opacity", 2)
      .attr("stroke", "black")
      .attr("proof", "Hello")
      .attr("radius", function() {
        return Math.sqrt(dim/(Math.sqrt(3)*3));
      });
  }
}


drawTriangles(number);

var mytriangle = d3.select(d3.selectAll("#id5").select("path").node());

console.log(mytriangle.attr("fill"))
          
    </script>
 </body>

To acquire the triangle within the group with ID number 5, you can utilize the following:

var mytriangle = d3.select(d3.selectAll("#id5").select("path").node());

For retrieving the fill of the triangle, you can employ attr as a getter:

console.log(mytriangle.attr("fill")) // returns rgb(128,141,30), a randomized value

To establish new values, you can utilize the function as a setter, as demonstrated in your code. For instance, in the following snippet, the triangle within the group with ID number 5 is selected and translated to 200,200:

<script src="https://d3js.org/d3.v4.min.js"></script>
 <body>
 <script>
    var width = window.innerWidth;
 var height = window.innerHeight;
 var number = 30;
 var body = d3.select("body");
 var triangle = d3.symbol()
    .type(d3.symbolTriangle);
var margins = 20;
var Group = [];
var borderSize = 10;

var svg = body.append("svg")
.attr("width", width)
.attr("height", height)
.style("border", "1px solid black");


 function drawTriangles(number) {
    for (var i = 0; i < number; i++) {
    Group[i] = svg.append("g")
        .attr("id",function(){ return "id" + i});
    var dim = Math.floor(Math.random() * 800 + 50);
    var r = Math.random()*360;
    Group[i].append("path")
      .attr("d", triangle.size(dim))
      .attr("transform", function (d) {
        var boundingBox = this.getBBox();
        var elementWidth = Math.ceil(boundingBox.width);
        var randomXOffset = Math.random() * (width - elementWidth - 2 * borderSize) + elementWidth/2 + borderSize;
        var randomYOffset = Math.random() * (height - elementWidth - 2 * borderSize) + elementWidth/2 + borderSize;
            return "translate(" + randomXOffset + "," + randomYOffset + ")rotate("+r+")";
        })
      .attr("fill", "rgb(" + parseInt(Math.random() * 255) + "," + parseInt(Math.random() * 255) + "," + parseInt(Math.random() * 255) + ")")
      .attr("opacity", 2)
      .attr("stroke", "black")
      .attr("proof", "Hello")
      .attr("radius", function() {
        return Math.sqrt(dim/(Math.sqrt(3)*3));
      });
  }
}


drawTriangles(number);

var mytriangle = d3.select(d3.selectAll("#id5").select("path").node());

mytriangle.transition().delay(500).duration(5000).attr("transform", "translate(200,200)");
          
    </script>
 </body>

Some issues in your code:

  • IDs should not start with a number
  • "opacity" values range from 0 to 1
  • Paths do not have a "radius" attribute.

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

What causes the error of inputRef.current being null in CurrencyTextField?

When attempting to target the second 'CurrentTextField' after changing the value of the first 'CurrentTextField', an error occurs stating 'inputRef.current is null'. import React, {useRef } from 'react'; import Curr ...

Warning: Unhandled promise rejection occurred while running the test

Currently delving into the world of selenium with a focus on testing the registration page. I've crafted a registration page class equipped with methods for monitoring registrations. However, upon attempting to execute a test within the application cl ...

Attempting to create a functional action listener for a deck of cards game

I'm currently working on a game and want to make an image appear blank when clicked on, to simulate it disappearing. Specifically, this is for a tri peaks solitaire game. I have a function that tests the validity of playing a card, but I'm strugg ...

Executing JavaScript in a web browser using Delphi

Similar Question: How to trigger the OnChange event of a "Select" element in Delphi WebBrowser? Hey there, I have a TWebBrowser in Delphi that loads a webpage containing a form with a dropdown menu. I am able to select an item from the dropdown, but ...

Some elements in the DOM appear to not be rendering even though they are present in the HTML source code

As a newcomer to web development, I have stumbled upon a perplexing issue. In my usage of d3.js (specifically the script found here), I have been attempting to incorporate additional features. I modified my JavaScript code to include a simple <p> ele ...

What is the process of retrieving an image file in a Java post API when it is being transmitted as form data through Jquery?

I have encountered an issue with fetching file data in my POST API when utilizing three input file fields in JavaScript. The values are being sent using formdata in jQuery upon clicking the submit button, but I am experiencing difficulties in retrieving th ...

Next step is to retrieve previous store information

As a newcomer to the world of Javascript and Reactjs, I encountered an issue while attempting to execute multiple actions upon clicking a button. The first action successfully updates the store data, however, the second action seems to be using the old sto ...

mandating the selection of checkboxes

Currently, I am exploring the possibility of automatically selecting a checkbox when an option is chosen from a dropdown menu. Below is a code snippet that demonstrates what I am aiming to tweak: $('.stackoverflow').on('change', func ...

What is the best way to integrate new entries into the data source of a Kendo UI grid?

After successfully creating a kendo.data.dataSource, I managed to bind it to the KendoUI Grid on my page. However, when attempting dataSource.insert(0, [a : "b"]);, it surprisingly removes the existing data. The code snippet that illustrates this issue i ...

"The Vue.js/JavaScript object updates, but the changes are not being displayed in the document object model (DOM

Currently, I am endeavoring to iterate through an array of objects and display them as list items. There is a click listener that introduces a custom property to the object, and a class binding depends on the value of that property. Would you mind reviewin ...

Retrieving POST request headers in Nightmare JS following a click() function execution and a wait() function delay

When I navigate a page, I input something in a field using type(), click on a button with click(), and then wait for an element to appear using wait(). I am interested in retrieving all the headers associated with the POST request that is triggered after ...

AngularJS: Issue with scope not updating across several views

Having one controller and two views presents a challenge. ClustersController angular.module('app.controllers').controller('ClustersController', [ '$scope', 'ClustersService', function($scope, ClustersService) { ...

I am attempting to adjust the color of the active tab, but I seem to be encountering issues in my code. Can anyone help me

The currently active tab should change along with the text inside the box, but it's not working as expected. I'm struggling to find out why. Here is a fiddle to demonstrate my progress so far: var btn1 = document.getElementById("btn1"); va ...

Tips for sending parameters in onClick within a React Functional Component

In my ReactJS Functional Component, I need to pass a few values when a button is clicked. The code snippet for this functionality is below: <span className="edit" onClick={ onClickEdit(value.title, value.details)}> <img src={editImg} height=" ...

Assign a value using the select component from Material UI

I just finished creating a dropdown menu const [selectedValue, setSelectedValue] = useState(''); const handleSelectionChange = (e: any) => { //setSelectedValue(e) console.log('value', selectedValue) } .... <Fo ...

Stopping Angular Route Alteration Depending on Routing Conditions

I have been searching everywhere for a solution to this issue. My goal is to be able to access the routing parameters collection and prevent the route from loading if a certain parameter is missing. I have tried using preventDefault in $routeChangeStart, b ...

Issues with CSS properties not functioning correctly within the class.col function

When attempting to apply specific CSS properties to a particular area (e.g., "Dashboard") by assigning the class name "main" to the div.col function in the HTML, I encountered an issue where the CSS property applied affected the entire page. The following ...

best practices for passing variables between multiple files within a nodejs application

// script.js var mydata = 1 module.exports = {mydata}; // file in my codebase var newData = require("../script.js") console.log(newData.mydata); // why is it undefined? I want to declare a variable as global across the entire project. I tried using ...

I have been tirelessly attempting to resolve this issue, yet all my efforts have proven futile thus

Encountering an issue with web packs and nextjs. import NextDocument, { Html, Head, Main, NextScript } from 'next/document' import theme from '../libs/theme.js' export default class Document extends NextDocument { render() { retu ...

Struggling to make the javascript function compatible with the drop-down menu

I'm encountering issues with making my JavaScript work properly alongside my HTML. Specifically, I want the "activity" drop-down box to function in conjunction with the "city" drop-down box. For instance, if I choose "Brisbane" and then select an acti ...