Multiple styles in one .style()?

3,426 views
Skip to first unread message

diafygi

unread,
Nov 2, 2011, 2:40:29 AM11/2/11
to d3-js
Howdy all,

I'm wondering if I can create a hash table with the styles that should
be applied to the shape. I'd prefer to not use CSS for the styles
because I will be converting the svg to png (via canvg), and CSS
styles don't carry through the svg encoding.

I'm thinking something like:
-----------------
var my_styles = {'stroke': "#000", 'fill': "#FFF", ...}

chart.selectAll("rect")
.data(data)
.enter().append("rect")
.style(my_styles)
....
-----------------

So does anyone know a way to add multiple style attributes at once?

Thanks!
Daniel

Mike Bostock

unread,
Nov 2, 2011, 12:19:29 PM11/2/11
to d3...@googlegroups.com
It's a work in progress:

https://github.com/mbostock/d3/pull/277

Mike

Mike Bostock

unread,
Nov 2, 2011, 12:32:55 PM11/2/11
to d3...@googlegroups.com
You can also do this by creating a reusable function. For example:

function myStyles(selection) {
selection
.style("stroke", "#000")
.style("fill", "#fff")

}

Then:

chart.selectAll("rect")
.data(data)
.enter().append("svg:rect")
.call(myStyles)

This lets you reuse attr and other operators too, of course.

Mike

Ryan Ewen

unread,
Nov 4, 2011, 5:13:42 PM11/4/11
to d3...@googlegroups.com
Maybe a function like this (untested):

function multiStyle (selector, styles) {
    var obj = d3.select(selector);

    for (var attr in styles){
        obj.style(attr, styles[attr]);     
    }
}

multiStyle('.something', {'fill': 'red', 'stroke': 2});

diafygi

unread,
Nov 4, 2011, 10:25:05 PM11/4/11
to d3-js
I was thinking something along those lines, too.

Mike Bostock

unread,
Nov 4, 2011, 10:26:59 PM11/4/11
to d3...@googlegroups.com
You could also do that as:

function styles(styles) {
return function(selection) {
for (var property in styles) {
selection.style(property, styles[property]);
}
};
}

Which you can then use as:

d3.selectAll(".something").call(styles({fill: "red", stroke: 2}));

Mike

Reply all
Reply to author
Forward
0 new messages