Joe
Joe

Reputation: 4254

D3 replaces objects

Got two functions:

 function drawWindows(windows, scale, svg){
        let myGroups = svg.selectAll('g').data(windows);
        let myGroupsEnter = myGroups.enter().append("g");
        myGroupsEnter.append("polygon")
            .style("fill", "green")
            ...
            });
  }



function drawDoors(doors, scale, svg){
            let myGroups = svg.selectAll('g').data(doors);
            let myGroupsEnter = myGroups.enter().append("g");
            myGroupsEnter.append("polygon")
                .style("fill", "red")
                ...
                });
      }

Then a main draw function:

function draw(){

        var svg = d3.select('#test').append('svg');
        var scale = ...
        var doors = [...]
        var windows = [...]
        drawWindows(..);
        drawDoors(..)
}

Problem is, the windows replaces the doors. And vice versa if I change order. How do I keep two separate functions and still draw both?

Upvotes: 0

Views: 32

Answers (1)

Cyril Cherian
Cyril Cherian

Reputation: 32327

You can do it by adding a class to the door and window selection, something like below:

 function drawWindows(windows, scale, svg){
        let myGroups = svg.selectAll('.window').data(windows);//select all with class window
        let myGroupsEnter = myGroups.enter().append("g").classed("window", true);
        myGroupsEnter.append("polygon")
            .style("fill", "green")
            ...
            });
  }



function drawDoors(doors, scale, svg){
            let myGroups = svg.selectAll('.door').data(doors);//select all with class door
            let myGroupsEnter = myGroups.enter().append("g").classed('door', true);
            myGroupsEnter.append("polygon")
                .style("fill", "red")
                ...
                });
      }

Upvotes: 2

Related Questions