Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement svg pattern via d3js?

Tags:

svg

d3.js

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 ?

like image 686
Hugolpz Avatar asked Dec 19 '22 07:12

Hugolpz


1 Answers

It's straight forward when we know the right xml syntax that you just provided :)

D3js pattern snippet

// 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>

Use

To use on your svg groups or elements:

g.attr("fill", "url(#hash4_4)" )

Concept

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.

Pattern's colors

Changing the pattern's fill will affect the elements using this pattern.

Other patterns

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

like image 141
Hugolpz Avatar answered Mar 07 '23 06:03

Hugolpz