首页 > 解决方案 > 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 d.x and d.y. 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?

标签: javascriptd3.js

解决方案


我假设你在printData之后打电话draw。如果是这种情况,您将看不到任何内容,因为您的“输入”选择为空(因此不会enter()调用之后的任何内容)。

在这种情况下,解决方案只是移动console.logtodraw或使用each()in printData

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

推荐阅读