简体   繁体   中英

How to print in console from d3 function

So I have this function to draw let's say rectangles:

draw(data) {
    this.canvas.selectAll('rect')
        .data(data)
        .enter()
        .append('rect')
        .attr('x', (d) => d.x)
        .attr('y', (d) => d.y)
        .attr('width', (d) => d.width)
        .attr('height', (d) => d.height)
        .style('fill', (d) => d.color);
}

and I want to print in console dx and dy I wrote this function:

printData(data) {
    this.canvas.selectAll('rect')
        .data(data)
        .enter()
        .append('rect')
        .attr('x', function(d) { console.log(d.x); });
}

but it isn't printing anything in console. Can anybody help me to tell what am I doing wrong here?

I'm assuming you're calling printData right after draw . If that's the case, you're not seeing anything because your "enter" selection is empty (hence nothing after enter() will be called).

The solution, that being the case, is just moving the console.log to draw or using an each() in printData :

printData(data) {
    this.canvas.selectAll('rect')
        .each(function(d) { 
            console.log(d.x); 
        });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM