add a variable object to svg

I’d like to append a variable “something” to an svg object made by d3.create.
For example

svg = d3.create("svg").attr("height",300).attr("width",300)
svg.append(thing)

where “thing” is for example a polygon with certain attributes, or a circle with attributes,
and that thing is returned from a function.

How does one do this?

Do you have a notebook that you’re working on as a starting point? There are so many potential variations on this theme that it’s hard to answer.

I’d point out, though, that the Simple D3 template does pretty much what you request. It generates circles whose cx and r attributes are generated by functions.

1 Like

I’m working on this notebook:

The specific problem I’d like to solve is that I’d like to pass a “tile” to the drawing function.
The tile might be a polygon, or a path, or a rectangle, or maybe someday an image. I understand how to set attributes of an object using variables but I don’t know how to set a different underlying object which might have different attributes. So I might want my “tile” to be a rectangle with specific attributes, or a path with different attributes, but those objects have different attribute families.

I hope this makes sense.

To answer your question directly, you might try something like so:

  let svg = d3.create("svg");
  svg.append(() => create_polygon());

where create_polygon returns an svg:polygon node. Here’s a working example.

Having said that, if you want to use wallpaper groups to generate tilings, I think you would get more idiomatic D3 code by using the group to generate data that describes the tiling (perhaps a list of transforms) and then using a construct like

svg.selectAll('polygon')
  .data(your_data)
  .join('polygon')
  .attr(.....)

I think that this will generally be more efficient than appending a bunch of polygons separately. I did something like that when generating Penrose tilings here:

Of course, Penrose tilings are not periodic like wallpaper tilings but the idea behind the code is similar.

1 Like

Your penrose tilings are great! Thanks for the help. I will probably refactor my code to use select as you suggest; my version is definitely clumsy.

1 Like