Search code examples
javascripthtmlsvgrect

I am trying to create a rect element within a svg element, but its not working


Why is the red rectangle not appearing when I run the function createRect(). Any help would be much appreciated.

function createRect() {
    var rec = document.createElement("rect");
    rec.style.width = "100px";
    rec.style.height = "100px";
    rec.style.left = "0px";
    rec.style.top = "0px";
    rec.style.fill = "red";
    rec.style.position = "absolute";
    var elem = document.getElementById("container");
    elem.append(rec);


}

window.onload = createRect;
<!DOCTYPE html> 
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tetris(test)</title> 
    <link rel="stylesheet" href="styleSheets/main.css">
    <script src = "https://code.jquery.com/jquery-3.4.1.js"></script>
    <script src = "js/jquery.1.js"></script>
    <script src = "js/main.js"></script>
  </head>
  <body>
      <svg id="container" width= "500" height= "650" style= "background-color: black" position= "relative">
      </svg>

  </body>
</html>

After I run this function onload, a red box should appear in the upper left corner.


Solution

  • maybe so

    <!DOCTYPE html> 
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Tetris(test)</title> 
        <link rel="stylesheet" href="styleSheets/main.css">
        <script src = "https://code.jquery.com/jquery-3.4.1.js"></script>
        <script src = "js/jquery.1.js"></script>
        <script src = "js/main.js"></script>
      </head>
      <body>
          <svg id="container" width= "500" height= "650" style= "background-color: black">
          </svg>
    
      </body>
    </html>
    
    <script>
    function createRect() {
    const svgNS = "http://www.w3.org/2000/svg";
    const svg = document.querySelector("svg");
    const rec = document.createElementNS(svgNS ,'rect');
    	rec.setAttribute('width', 100);
    	rec.setAttribute('height', 100);
    	rec.setAttribute('x', 50);
    	rec.setAttribute('y', 50);
    	rec.setAttribute('fill', 'red');
      
     svg.appendChild(rec);
    }
    
    window.onload = createRect;
    
    
    </script>