Home > Software engineering >  Drawing an SVG line diagonally across its containing DIV (and maintaining as DIV resized)
Drawing an SVG line diagonally across its containing DIV (and maintaining as DIV resized)

Time:10-13

I am trying to draw an SVG line diagonally across a div like this:

enter image description here

I can create a div with an SVG line inside:

<div id="my_div" class="rectangle">
    <svg id="my_line" width='100%' height='100%' viewBox='0 0 2000 2000' preserveAspectRatio='none'><line style='red; stroke-width:2' /></svg>
</div>

Since I can resize the containing rectangle div, I need the SVG line to move with the rectangle div as it's resized, always touching the top left and bottom right corners.

I try to use getBoundingClientRect to set the line positions:

var rect_box = document.getElementById("my_div").getBoundingClientRect();

$("#my_line").attr("x1", rect_box.left)
$("#my_line").attr("y1", rect_box.top)
$("#my_line").attr("x2", rect_box.right)
$("#my_line").attr("y2", rect_box.bottom)

But this doesn't work. Is there a way to set the viewBox, or apply CSS, such that the SVG line always remains fixed across the diagonal of its containing div?

Note: There's also this approach that uses CSS clip path, and it remains fixed to its corners during resizing, but the thickness of the line changes as it's resized. I need the line thickness to remain constant.

CodePudding user response:

No javascript required.

#my_div {
  outline: 1px solid;
  height: 200px;
}
<div id="my_div">
  <svg width='100%' height='100%' viewBox='0 0 100 100' preserveAspectRatio='none'>
       <line x1="0" y1="0" x2="100" y2="100" vector-effect="non-scaling-stroke" stroke="red" />
    </svg>
</div>

  • Related