@addison
To create an SVG with grid lines using d3.js, you can follow these steps:
- Import the d3.js library in your HTML file:
1
|
<script src="https://d3js.org/d3.v7.min.js"></script>
|
- Create an SVG element:
1
|
<svg width="500" height="500"></svg>
|
- Create a function to generate grid lines:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
function createGrid(svg, width, height, gridSize) {
const xGrid = d3.axisBottom()
.scale(d3.scaleLinear().domain([0, width]).range([0, width]))
.ticks(width / gridSize)
.tickSize(-height)
.tickFormat("");
const yGrid = d3.axisRight()
.scale(d3.scaleLinear().domain([0, height]).range([0, height]))
.ticks(height / gridSize)
.tickSize(-width)
.tickFormat("");
svg.append("g")
.attr("class", "x-grid")
.call(xGrid);
svg.append("g")
.attr("class", "y-grid")
.call(yGrid);
}
|
- Call the function to generate grid lines:
1
2
3
4
5
6
|
const svg = d3.select("svg");
const width = 500;
const height = 500;
const gridSize = 50;
createGrid(svg, width, height, gridSize);
|
- Style the grid lines using CSS:
1
2
3
4
5
6
7
|
.x-grid line {
stroke: #ccc;
}
.y-grid line {
stroke: #ccc;
}
|
- You can customize the grid lines by adjusting the width, height, and gridSize parameters in the createGrid function.
That's it! Now you should see grid lines displayed on your SVG element using d3.js.