tog tog - 1 month ago 16
CSS Question

d3 built specifi icon from data

I want to display a kind of specific icon in different boxes using d3.
I have a data as an array of

[x0, y0, x1, y1, vx, vy]
where:


  • x0, y0 is the first corner of a box,

  • x1, y1 the second corner and

  • vx, vy two parameters (velocity)



that will be used to generate a SVG path.

I am using:

var boxes = nodeSVGGroup.selectAll("rect").data(nodes).enter().append("rect");


to generate my boxes and this is working well

My problem comes when I want to create the SVG path (icon) and properly render it in each box (it needs to be generated, translated and rotated to fit the center of each box.

I am using a similar pattern i.e.

var selection = nodeSVGGroup.selectAll(".barb").data(nodes);

selection.enter()
.append('g')
.each(function(node, i) {
var vx = node[4];
var vy = node[5];

var speed = Math.sqrt(vx*vx + vy*vy);
var angle = Math.atan2(vx, vy);

// generate a path based on speed. it looks like
// M2 L8 2 M0 0 L1 2 Z
var path = ...
var scale = 0.5*(node[1]-node[0])/8;

var g = d3.select(this).data([path,angle,scale]).enter().append('g');

// still need to add following transforms
// translate(' + node[2] + ', ' + node[3] + ')
// scale(' + scale + ')
// rotate(' + angle + ' ' + 0 + ' ' + 0 + ')
// translate(-8, -2)',

g.append('path').attr('d', function(d){console.log(d); return d[0];})
.attr('vector-effect', 'non-scaling-stroke');
})
.attr('class', 'wind-arrow');


I get that error
Uncaught TypeError: Cannot read property 'ownerDocument' of null(…)
which seems to be related to this line

.each(function(node, i) {


What am I doing wrong?

The full code is here

Thanks

Answer

It's not entirely clear why are you trying to create an enter selection inside an each. I'm not sure if I understand your goals, but you can simply use d3.select(this) to append the path to each group:

d3.select(this).append('path')
    .attr('d', function(d){ return path;})

Here is the updated fiddle: https://jsfiddle.net/9x169eL1/