Home > front end >  Creating a mutable SVG with Javascript
Creating a mutable SVG with Javascript

Time:06-13

I would like to create a resizable SVG using JavaScript. If you run the code, you'll notice the "svgTriangle[0].innerHTML = "<polygon points='";" line does not get appended inside the SVG tag. If someone could help me figure out why this is not getting appended, I would greatly appreciate it. Thanks.

var svgTriangle = document.getElementsByClassName("svg-triangle");
var bgTrianglePoints;

function updateOnResize() {
  bgTrianglePoints = [
    [0, 0],
    [window.innerWidth * 0.76, 0],
    [window.innerWidth * .16, window.innerHeight * 1.2],
    [0, window.innerHeight * 1.2]
  ];

  svgTriangle[0].innerHTML = "<polygon points='";
  for (var i = 0; i < bgTrianglePoints.length; i  ) {
    svgTriangle[0].innerHTML  = bgTrianglePoints[i][0]   ","   bgTrianglePoints[i][1]   " ";
  }
  svgTriangle[0].innerHTML  = "'/>";
}

window.onresize = function() {
  updateOnResize();
}

updateOnResize();
html,
body {
  margin: 0px;
  padding: 0px;
}

#header {
  width: 100vw;
  height: 85vh;
}

.svg-triangle {
  width: 100%;
  height: 100%;
  fill: red;
}
<div id="header">
  <svg xmlns="http://www.w3.org/2000/svg" ></svg>
</div>

CodePudding user response:

To answer your question, why the first line does not appear in the HTML, it is probably because it makes the HTML invalid. You could instead use the document.createElementNS method as follows:

const polygon = document.createElementNS("http://www.w3.org/2000/svg", "polygon");

to create the polygon element in the SVG namespace.

Then, you can create the string for the points attribute:

let points = "";

for (var i = 0; i < bgTrianglePoints.length; i  ) {
    points  = bgTrianglePoints[i][0]   ","   bgTrianglePoints[i][1]   " ";
  }

and finally set the attribute on the element:

polygon.setAttribute("points", points);

Now, you can use svgTriangle.appendChild(polygon) to add the polygon to the HTML.

Another possibility is to use the points property on the polygon element, which is an SVGPointList and use appendItem on it in a loop to add the points, but that is quite much code and not really necessary. Also, SVGPoint is already deprecated...

  • Related