d3. js круги не отображаются после попытки использовать шаблон обновления - PullRequest
0 голосов
/ 06 августа 2020

Опять я - возможно, однажды я помогу. Но на данный момент я полностью потерялся. (Я совершенно новичок в d3. js, и мои javascript знания очень базовые c на данный момент)

Итак ... я пытаюсь сделать интерактивную визуализацию персонажа и их отношение. Планируется начать с одного Персонажа (того, кто вошел в систему) и сначала показать его отношения. Теперь, когда пользователь щелкает по своему узлу, должно произойти magi c и появятся отношения между узлом, на котором щелкнули мышью, ... и так далее. (в процессе пользователь также должен иметь возможность снова скрывать узлы, но маленькие шаги ...: D)

Итак, я загрузил код и свои файлы json в git концентратор, вы можете его найти здесь: https://github.com/katjalennartz/ba (index2. html должен показать все, что код js находится в noForce2. js)

Я почти уверен, что проблема в том, что нет круга показанное зависит от моих групп, и что там я все испортил. Я не уверен, как правильно связать мои данные, чтобы можно было перетаскивать узлы (и чтобы ссылки и текст следовали за узлами ...)

Это часть, в которой я почти уверен , который не работает:

        .selectAll("circles") // was null before try to use an update function -> null for save index 0 from missing when append circles. but null now is not working
            .data(rootNodes)
  
        //Exit (remove old elements)
        circleGroup.exit().remove;
        
        //Enter data 
        circleGroup.enter()
            .append('g')
            .attr('transform', function (d) {
                return 'translate(' + d.x + ',' + d.y + ')'; //work not nested data
            })
            .call(d3.drag() //need the drag so you can play with the nodes - links should follow - try to group it for show text beside circle
                .on("start", dragstarted)
                .on("drag", dragged)
                .on("end", dragended));
        
        //add the circle 
        circleGroup.append("circle")
            .attr("r", function (d) {
                //increase radius if current user 
                if (d.id === thisuser) {
                    return radius * 2
                } else { return radius; }
            })
            .attr("class", "chara")
            .attr("fill", function (d) {
                //set color to red if current user 
                return (d.id === thisuser) ? "red" : "blue"
            })
            .style("stroke", "#ffffff")
            .on("click", update); //this should call the update
        
        //set text to circle (username)
        circleGroup.append("text")
            .text(function (d, i) { return d.username; })
            //.style('text-anchor', 'top')
            .attr("x", radius)
            .attr("y", 4);

возможно, кто-то здесь может помочь мне убрать этот беспорядок, я был бы полностью благодарен

1 Ответ

0 голосов
/ 07 августа 2020

Проблема в ссылке на circleGroup. Когда вы впервые используете circleGroup, вы делаете следующее:

var circleGroup = svg
    .selectAll("g") 
    .data(rootNodes)

Прямо сейчас circleGroup - это выбор update. Именно при использовании enter() или exit() он становится желаемым выбором для ввода. Это сделано правильно здесь:

circleGroup.enter() // Enter selection
    .append('g')
    .attr('transform', function (d) {
        return 'translate(' + d.x + ',' + d.y + ')';
    })
    .call(d3.drag() 
        .on("start", dragstarted)
        .on("drag", dragged)
        .on("end", dragended));

, но не здесь:

circleGroup.append("circle") // no enter(), so update selection
    .attr("r", function (d) {
        if (d.id === thisuser) {
            return radius * 2
        } else { return radius; }
    })
    .attr("class", "chara")
    .attr("fill", function (d) {
        return (d.id === thisuser) ? "red" : "blue"
    })
    .style("stroke", "#ffffff")
    .on("click", update);

Что вы можете сделать, так это напрямую использовать enter () в переменной circleGroup, чтобы она представляла выбор ввода . Если вам также нужно использовать выбор обновления и выхода, используйте другую переменную:

var circleGroup = svg
    .selectAll("g") 
    .data(rootNodes) // update

var circleGroupEnter = circleGroup.enter()

circleGroupEnter
    .append("circle")
    .append('g')
    .attr('transform', function (d) {
        return 'translate(' + d.x + ',' + d.y + ')'; //work not nested data
    })
    .call(d3.drag() //need the drag so you can play with the nodes - links should follow - try to group it for show text beside circle
        .on("start", dragstarted)
        .on("drag", dragged)
        .on("end", dragended));

        
circleGroupEnter
    .attr("r", function (d) {
        if (d.id === thisuser) {
            return radius * 2
        } else { return radius; }
    })
    .attr("class", "chara")
    .attr("fill", function (d) {
        return (d.id === thisuser) ? "red" : "blue"
    })
    .style("stroke", "#ffffff")
    .on("click", update);

Использование selection.join()

Вышеупомянутое немного сложно. Вы можете использовать selection.join() для упрощения - чтобы понять, как это работает, см. Этот учебник .

var circleGroup = svg
    .selectAll("g") 
    .data(rootNodes)

circleGroup
    .join('g')
    .attr('transform', function (d) {
        return 'translate(' + d.x + ',' + d.y + ')';
    })
    .call(d3.drag() 
        .on("start", dragstarted)
        .on("drag", dragged)
        .on("end", dragended));

        
circleGroup
    .join("circle")
    .attr("r", function (d) {
        if (d.id === thisuser) {
            return radius * 2
        } else { return radius; }
    })
    .attr("class", "chara")
    .attr("fill", function (d) {
        return (d.id === thisuser) ? "red" : "blue"
    })
    .style("stroke", "#ffffff")
    .on("click", update);

selection.join() также работает для обработки трех вариантов выбора: вот пример из более позднего в вашем коде:

var link = svg.append("g")
    .attr("class", "link")
    .selectAll("line")
    .data(rootLinks);
        
link.join(
    enter => enter.append('line'),
    update => update,
    exit => exit.remove()
)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...