Creating Extra D3.js Characters

D3 already contains a bunch of characters , but I would like to add a custom one. So that I can, for example, just call d3.svg.symbol().type('custom') in my code.

+7
source share
1 answer

This cannot be done directly because the array of character definitions is not accessible from the API.

In the source code HERE, you can see that the symbol definitions are stored in d3.map called d3_svg_symbols . The only part of this map that is exposed to the public API is the key array. This is done by calling the .keys() method of the card, HERE .

 d3.svg.symbolTypes = d3_svg_symbols.keys(); 

Definitions themselves are never displayed, so you cannot add definitions directly as you hoped.

However, you can create a workaround without too much difficulty. One way is to create a map of your custom characters and create a function based on the existing one for the embedded characters. For example:

 // DEFINE A COUPLE OF CUSTOM SYMBOLS var customSymbolTypes = d3.map({ 'custom-symbol-1': function(size) { // returns a path-data string }, 'custom-symbol-2': function(size) { // returns a path-data string } }); // CREATE A CUSTOM SYMBOL FUNCTION MIRRORING THE BUILT-IN FUNCTIONALITY d3.svg.customSymbol = function() { var type, size = 64; // SET DEFAULT SIZE function symbol(d,i) { // GET THE SYMBOL FROM THE CUSTOM MAP return customSymbolTypes.get(type.call(this,d,i))(size.call(this,d,i)); } // DEFINE GETTER/SETTER FUNCTIONS FOR SIZE AND TYPE symbol.type = function(_) { if (!arguments.length) return type; type = d3.functor(_); return symbol; }; symbol.size = function(_) { if (!arguments.length) return size; size = d3.functor(_); return symbol; }; return symbol; }; 

Then you can create a function to check if the character is in the list of built-in characters, and if not, suppose it's a custom character:

 function getSymbol(type, size) { // SIZE DEFAULTS TO 64 IF NOT GIVEN size = size || 64; // IF TYPE IS ONE OF THE BUILT-IN TYPES, CALL THE BUILT-IN FUNCTION if (d3.svg.symbolTypes.indexOf(type) !== -1) { return d3.svg.symbol().type(type).size(size)(); } // OTHERWISE, CALL THE CUSTOM SYMBOL FUNCTION else { return d3.svg.customSymbol().type(type).size(size)(); } } 

HERE is a demonstration of this method in action.

I admit that it seems crazy to realize the whole function of a character again. It might be worth pointing out a function request on the github page asking for a custom map of character definitions that could be read into the built-in method. Anyway, I hope this helps.

+12
source share

All Articles