0

Using HTML, vanilla JS and D3.js, I want to draw a number of simple SVG 'rect' shapes based on the number of objects in an array.

const data = [
    { width: 200, height: 100, fill: "red" },
    { width: 100, height: 60, fill: "pink" },
    { width: 50, height: 30, fill: "red" },
]; 

My approach is to first insert a 'rect' element for every object in the array into a hard-coded svg canvas in the html file.

const svg2 = document.getElementsByTagName('svg')[0];
data.forEach( function() {
        newrect = document.createElement('rect');   //create a rect
        svg2.appendChild(newrect);                 //append to the doc.body
    });

Then I am using D3 to add the attributes from the data objects to the created 'rect' elements.

const svg = d3.select("svg"); 
const rect = svg.selectAll("rect")
    .data(data)
    .attr("width", d => d.width)
    .attr("height", d => d.height)
    .attr("fill", d => d.fill)

When I run the code in Chrome, everything looks fine in the inspector: I can see the right number of 'rect' elements with the correct attributes.

Still, I cannot see the shapes.

Code run in Chrome

I know that there are ways to solve this with D3, but I would like to understand what is going on and if there are any potential solutions using only vanilla JS.

Thank you!

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>SVG Basics</title>
</head>
<body>
  
<div class="canvas">
  <svg width="600" height="600">
  </svg>
</div>

  <script src="https://cdn.jsdelivr.net/npm/d3@7"></script>
  <script>
    const div = d3.selectAll("div");
  </script>
  <script src="index.js"></script>

</body>
</html>
  • You will need to use the `document.createElementNS("http://www.w3.org/2000/svg", 'rect');` – Keith Jun 17 '21 at 09:06
  • If you need to create SVG element a lot, what I do is use a helper function,. Also for those who use Typescript and still want the types to work, this is what I use -> `function SVGElement(a: T) { return document.createElementNS("http://www.w3.org/2000/svg", a); } ` – Keith Jun 17 '21 at 09:12

0 Answers0