MayaGans
MayaGans

Reputation: 1845

D3 Binding Text and SVG

I'm creating my first d3.js project with circles that can be dragged, added, or removed with centered text, but I can't seem to bind the text to the circle. I've seen some questions similar to mine, but I hope this is different enough because I tried applying the solutions but they didn't work. I'm not only looking for a solution but I'd like to know what I'm doing wrong here.

Any insights would be extremely helpful!

I tried creating a group variable group and assumed I could use that to bind the two elements. What's wrong with my mental model?

chart = {

  const dataset = [
  {start: new Date("2019-09-23 1:00 AM"), target: 70},
  {start: new Date("2019-09-23 8:00 AM"), target: 75},
  {start: new Date("2019-09-23 9:00 PM"), target: 70},
  {start: new Date("2019-09-23 1:00 PM"), target: 75},
  {start: new Date("2019-09-23 5:00 PM"), target: 70},
  {start: new Date("2019-09-23 6:00 PM"), target: 65},
]

  var xScale = d3.scaleLinear()
    .domain([0, d3.max(dataset, function(d) {
      return d.x_pos
    })]).range([0, width]);

  const svg = d3.create("svg")
      .attr("viewBox", [0, 0, width, height])
      .attr("stroke-width", 2);

    svg.append("g")
      .call(xAxis)

  var group = svg.selectAll('g')
  .data(dataset)
  .enter()
  .append("g")
  .attr("transform", 
        "translate(" + margin.left + "," + margin.top + ")")

   group.append("circle")
     .data(dataset)
     .enter()
     .append("circle")
     .join("circle")
     .attr("cx", d => x(d.start))
     .attr("cy", 55)
     .attr("r", 30)
     .attr("fill", "red")
     .call(d3.drag()
      .on("start", dragstarted)
      .on("drag", dragged)
      .on("end", dragended))
    .on("click", removeElement);

  group.append("text")
    .data(dataset)
    .enter()
    .append("text")
    .attr("x", function(d) { return x(d.start) - 10; })
    .attr("y", function(d) { return 60; })
    .style("fill", "white")
    .text(function(d) { return d.target })
   .call(d3.drag()
    .on("drag", dragged))
   .on("click", removeElement)


  svg.on("click", function() {
    var coords = d3.mouse(this);

    var newData = {
      x: d3.event.x,
      y: d3.event.y,
      target: 0
    };

    dataset.push(newData);

    group.append("circle")
      .attr("cx", function(d) {
        return x(d.start);
      })
      .attr("cy", function(d) {
        return 55;
      })
      .attr("r", 30)
      .style("fill", "red")
      .attr('id', function(d, i) {
        return 'circle_' + i;
      })
      .call(d3.drag()
        .on("start", dragstarted)
        .on("drag", dragged)
        .on("end", dragended))
      .on("click", removeElement);

    group.append("text")
    .data(dataset)
    .enter()
    .append("text")
    .attr("x", function(d) { return x(d.start) - 10; })
    .attr("y", function(d) { return 60; })
    .style("fill", "white")
    .text(function(d) { return d.target })
   .call(d3.drag()
   .on("drag", dragged))
   .on("click", removeElement)

  })

  function dragstarted(d) {
    d3.select(this).raise().attr("stroke", "black");
  }

  function dragged(d) {
    // tried adding .select("circle") from prior SO posts
    d3.select(this)
      .attr("cx", d.x = d3.event.x)
      .attr("cy", d.y = 55);
    d3.select(this) //.select("text")
      .attr("x", d.x = d3.event.x - 10)
      .attr("y", d.y = 60);
  }

  function dragended(d) {
       d3.select(this).attr("stroke", null);
  }

  function removeElement(d) {
    d3.event.stopPropagation()
    d3.select(this)
      .remove();
  }

  return svg.node();
}
x = d3.scaleTime()
    .domain([new Date("2019, 9, 23 12:00 AM"), new Date("2019, 9, 23, 11:59 PM")])
    .rangeRound([margin.left, width - margin.right])

interval = d3.timeHour.every(1)

xAxis = g => g
    .attr("transform", `translate(0,${height - margin.bottom})`)
    .call(g => g.append("g")
        .call(d3.axisBottom(x)
            .ticks(interval)
            .tickSize(-height + margin.top + margin.bottom)
            .tickFormat(() => null))
        .call(g => g.select(".domain")
            .attr("fill", "#ddd")
            .attr("stroke", null))
        .call(g => g.selectAll(".tick line")
            .attr("stroke", "#fff")
            .attr("stroke-opacity", d => d <= d3.timeHour(d) ? 1 : 0.5)))
    .call(g => g.append("g")
        .call(d3.axisBottom(x)
            .ticks(d3.timeHour)
            .tickPadding(0))
        .attr("text-anchor", null)
        .call(g => g.select(".domain").remove())
        .call(g => g.selectAll("text").attr("x", 6)))

margin = ({top: 10, right: 0, bottom: 20, left: 0})
height = 120
d3 = require("d3@5")

Link to notebook: https://observablehq.com/d/c0b23251c8bdafa2

Upvotes: 1

Views: 228

Answers (1)

andrea06590
andrea06590

Reputation: 1299

You need to see svg as a group of elements, where the elements can also be groups of elements.

What does it looks like to have a circle with a text inside of it ?

<svg...>
    <g id="myGroup">
          <circle style="" cx="250" cy="250" r="245"></circle>
          <text x="50%" y="50%" stroke="#111"> Hello !</text>
    </g>
</svg>

Now if you want to generate this svg from scratch :

var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
var group = document.createElementNS("http://www.w3.org/2000/svg","g");
group.setAttribute("id","myGroup")
var newCircle = document.createElementNS(svgNS,"circle"); 
var newText = document.createElementNS(svgNS,"text");
newText.setAttributeNS(null,"x", "50%");     
newText.setAttributeNS(null,"y", "50%"); 
document.getElementById("svg").appendChild(myGroup);
document.getElementById("myGroup").appendChild(newCircle);

The circle and the text are bind into a group. Then drag your group, and not your circle ;)

Upvotes: 1

Related Questions