Home > Software engineering >  Javascript SVG Rectangle Gets Cut Off
Javascript SVG Rectangle Gets Cut Off

Time:11-27

New to JavaScript. And SVG. So yeah. Any help for this newbie is really appreciated.

Picture posted as well. This is a rounded rectangle, but I can't actually get it to grow any larger than it is. It's like it gets cropped on the bottom and right sides. I'm sure this is really simple, but it's just blocked me completely.

Ultimately, I'd like this rectangle to span the width of the page.

enter image description here

Here's my code:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>POC</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
    <link type="text/css">
</head>
<body>
    <div id="main">
        <svg id="mySVG" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"></svg>
   </div>
    <script type="module">
        var svgNS = "http://www.w3.org/2000/svg";  
        function makeShape1() {
            var shape = document.createElementNS(svgNS, "rect");
            shape.setAttributeNS(null, "x", 5);
            shape.setAttributeNS(null, "y", 5);
            shape.setAttributeNS(null, "rx", 5);
            shape.setAttributeNS(null, "ry", 5);
            shape.setAttributeNS(null, "width",  400);
            shape.setAttributeNS(null, "height", 400);
            shape.setAttributeNS(null, "fill", "green");         
            document.getElementById("mySVG").appendChild(shape);
        }
        makeShape1();
    </script>
</body>
</html>
 

CodePudding user response:

You just need a viewBox really.

I started it at (5, 5) but you might want to start it at (0, 0) you'll have to increase the width and height if you do that though. E.g. viewBox="0 0 410 410"

<!DOCTYPE html>
<html lang="en">
<head>
    <title>POC</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
    <link type="text/css">
</head>
<body>
    <div id="main">
        <svg id="mySVG" viewBox="5 5 400 400" preserveAspectRatio="none"></svg>
   </div>
    <script type="module">
        var svgNS = "http://www.w3.org/2000/svg";  
        function makeShape1() {
            var shape = document.createElementNS(svgNS, "rect");
            shape.setAttributeNS(null, "x", 5);
            shape.setAttributeNS(null, "y", 5);
            shape.setAttributeNS(null, "rx", 5);
            shape.setAttributeNS(null, "ry", 5);
            shape.setAttributeNS(null, "width",  400);
            shape.setAttributeNS(null, "height", 400);
            shape.setAttributeNS(null, "fill", "green");         
            document.getElementById("mySVG").appendChild(shape);
        }
        makeShape1();
    </script>
</body>
</html>

  • Related