I would like to add a pattern to some of my svg map's polygons via d3js, the disputed areas. I already add thesr geographic shapes well, I also saw svg patterns are possible in native svg :
<svg width="120" height="120" viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<pattern id="Triangle" width="10" height="10" patternUnits="userSpaceOnUse">
<path fill="black"d="M5,0 10,10 0,10 Z" />
</pattern>
</defs>
<circle cx="60" cy="60" r="50" fill="url(#Triangle)" />
</svg>
But how to add hash patterns to my d3js geographic shapes ?
It's straight forward when we know the right xml syntax that you just provided :)
// SVG injection:
var svg = d3.select("#hook").append("svg").attr("id", "d3svg")
.attr("width", 120)
.attr("height", 120);
//Pattern injection
var defs = svg.append("defs")
var pattern = defs.append("pattern")
.attr({ id:"hash4_4", width:"8", height:"8", patternUnits:"userSpaceOnUse", patternTransform:"rotate(-45)"})
.append("rect")
.attr({ width:"4", height:"8", transform:"translate(0,0)", fill:"#88AAEE" });
//Shape design
svg.append("g").attr("id","shape")
.append("circle")
.attr({cx:"60",cy:"60",r:"50", fill:"url(#hash4_4)" })
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="hook"></div>
To use on your svg groups or elements:
g.attr("fill", "url(#hash4_4)" )
Going backward, any diagonal strip is a rotated vertical hash. The basic pattern of a vertical hash is a square area, of which a part is a vertical line taking more or less of the horizontal width, by example 4px colored out of 8px width for the square. Repeat this pattern, rotate, and you have it.
Changing the pattern's fill will affect the elements using this pattern.
Similarly, you can include more complex svg pattern by designing paths within a square. By example via:
pattern.append("path").attr("d", "M5,0 10,10 0,10 Z")
// small triangle but can be pushed further !
For a gist on svg path, check svg path & commnands.
Demo fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With