Добавлен элемент DOM через D3 не отображается - PullRequest
0 голосов
/ 10 октября 2018

Я пытаюсь добавить текст в диаграмму (createLegend()).

http://jsfiddle.net/gs6rehnx/2045/

<button type="button" onclick="createPie()">Click Me First!</button>
<button type="button" onclick="updatePie()">Update Diagram!</button>
<div class='foo'></div>


const width = 260;
const height = 260;
const thickness = 40;
const duration = 750;

const radius = Math.min(width, height) / 2;
const color = d3.scaleOrdinal(d3.schemeCategory10);

const arc = d3
  .arc()
  .innerRadius(radius - thickness)
  .outerRadius(radius);

const pie = d3
  .pie()
  .value(function(d) {
    return d.value;
  })
  .sort(null);


const create = function(data) {
  const svg = d3
    .select('.foo')
    .append('svg')
    .attr('class', 'pie')
    .attr('width', width)
    .attr('height', height)
    .attr('id', 'svgClass');

  svg
    .append('g')
    .attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')')
    .attr('id', 'bar');
    createLegend();
  draw(data);
}

const draw = function(data) {
  const path = d3.select('#bar')
    .selectAll('path')
    .data(pie(data))

  path
    .enter()
    .append('g')
    .append('path')
    .attr('d', arc)
    .attr('fill', (d, i) => color(i));

  path
    .transition()
    .duration(duration)
    .attrTween('d', function(d) {
      const interpolate = d3.interpolate({
        startAngle: 0,
        endAngle: 0
      }, d);
      return function(t) {
        return arc(interpolate(t));
      };
    });
};

const createLegend = function() {
    d3.select('#svgClass')
  .append('text')
  .text('foo bar')
  .attr('position', 'relative')
  .attr('background-color', 'red')
  .attr('top', '50px')
  .attr('left', '50px')
}


const data = [{
    name: 'USA',
    value: 50
  },
  {
    name: 'UK',
    value: 5
  },
  {
    name: 'Canada',
    value: 5
  },
  {
    name: 'Maxico',
    value: 40
  }
]

function createPie() {
  create(data)
}

const newData = [{
    name: 'USA',
    value: 40
  },
  {
    name: 'UK',
    value: 20
  },
  {
    name: 'Canada',
    value: 30
  },
  {
    name: 'Maxico',
    value: 10
  }
];

function updatePie() {
  draw(newData)
}

Это отображается в DOM tree, когда я проверяю диаграмму,Тем не менее, его не отображается на сайте.Почему это так?

Ответы [ 2 ]

0 голосов
/ 10 октября 2018

Убедитесь, что вы прочитали текстовые документы SVG , чтобы узнать, как применить позиционирование к text.

Причина, по которой вы не видите текст, состоит в том, что он полностью выходит за пределы,CSS позиционирование не является методом позиционирования текста.Используйте атрибуты x и y ИЛИ используйте transform ( SVG-преобразование ).

Вот измененный createLegend код:

d3.select('#svgClass')
  .append('text')
  .text('foo bar')
  .attr('x', width/2).attr('y', height/2).style('fill', 'red');

Теперь яобратите внимание, что вы пытаетесь добавить background-color к тексту, который в случае SVG можно сделать, используя rect за текстом.Вот пример: d3 способ добавления фона к текстам

Фрагмент:

const width = 260;
const height = 260;
const thickness = 40;
const duration = 750;

const radius = Math.min(width, height) / 2;
const color = d3.scaleOrdinal(d3.schemeCategory10);

const arc = d3
  .arc()
  .innerRadius(radius - thickness)
  .outerRadius(radius);

const pie = d3
  .pie()
  .value(function(d) {
    return d.value;
  })
  .sort(null);


const create = function(data) {
  const svg = d3
    .select('.foo')
    .append('svg')
    .attr('class', 'pie')
    .attr('width', width)
    .attr('height', height)
    .attr('id', 'svgClass');

  svg
    .append('g')
    .attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')')
    .attr('id', 'bar');
	createLegend();
  draw(data);
}

const draw = function(data) {
  const path = d3.select('#bar')
    .selectAll('path')
    .data(pie(data))

  path
    .enter()
    .append('g')
    .append('path')
    .attr('d', arc)
    .attr('fill', (d, i) => color(i));

  path
    .transition()
    .duration(duration)
    .attrTween('d', function(d) {
      const interpolate = d3.interpolate({
        startAngle: 0,
        endAngle: 0
      }, d);
      return function(t) {
        return arc(interpolate(t));
      };
    });
};

const createLegend = function() {
	d3.select('#svgClass')
  .append('text')
  .text('foo bar').attr('x', width/2).attr('y', height/2).style('fill', 'red');
}


const data = [{
    name: 'USA',
    value: 50
  },
  {
    name: 'UK',
    value: 5
  },
  {
    name: 'Canada',
    value: 5
  },
  {
    name: 'Maxico',
    value: 40
  }
]

function createPie() {
  create(data)
}

const newData = [{
    name: 'USA',
    value: 40
  },
  {
    name: 'UK',
    value: 20
  },
  {
    name: 'Canada',
    value: 30
  },
  {
    name: 'Maxico',
    value: 10
  }
];

function updatePie() {
  draw(newData)
}
<script src="https://d3js.org/d3.v4.min.js"></script>

<button type="button" onclick="createPie()">Click Me First!</button>
<button type="button" onclick="updatePie()">Update Diagram!</button>
<div class='foo'></div>

Надеюсь, это поможет.

0 голосов
/ 10 октября 2018

Все сводится к различиям между HTML и SVG.К сожалению, вам нужно использовать несколько разных атрибутов.

Во-первых left и top не верны, вы хотите использовать x и y соответственно.

Во-вторых background-color не сработает, вместо этого попробуйте применить stroke или fill к вашему тексту.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...