Home > Mobile >  Drawing a line between html div elements
Drawing a line between html div elements

Time:09-18

I saw this example in w3schools where you set svg line attributes like x1, y1, x2, y2 and a line appears on screen. I am using same method to draw svg line between div elements using javascript and it doesn't seem to work.

I have two circle from which I read there x and y values using boundingClientRect in javascript and setting it on svg line using set attribute. I want line connecting those two circles

Here is my code

const circle1 = document.querySelector('.circle--1');
const circle2 = document.querySelector('.circle--2');

const line1 = document.querySelector('#line-1');

line1.setAttribute('x1', circle1.getBoundingClientRect().x);
line1.setAttribute('y1', circle1.getBoundingClientRect().y);
line1.setAttribute('x2', circle2.getBoundingClientRect().x);
line1.setAttribute('y2', circle2.getBoundingClientRect().y);
*,
*::before,
*::after {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html {
  font-size: 62.5%;
}

body {
  font-family: sans-serif;
}

.header {
  width: 100%;
  height: 57rem;
  background-image: linear-gradient(to right, #64b5f6, #1976d2);
  padding: 0 2rem;
}

.graph {
  width: 100%;
  max-width: 120rem;
  background-color: grey;
  height: 100%;
  position: relative;
}

.circle {
  width: 5rem;
  height: 5rem;
  border-radius: 50%;
  background-color: white;
  font-size: 2rem;
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
}

.circle--1 {
  left: 0;
  bottom: 5%;
}

.circle--1 {
  left: 10%;
  bottom: 60%;
}

.circle--2 {
  right: 10%;
  bottom: 60%;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="./style.css" />
    <title>Connect Divs</title>
  </head>
  <body>
    <header class="header">
      <div class="graph">
        <div class="circle circle--1">1</div>
        <div class="circle circle--2">2</div>

        <svg>
          <line
            id="line-1"
            style="stroke: rgb(255, 255, 255); stroke-width: 3"
          />
        </svg>
      </div>
    </header>

    <script src="./script.js"></script>
  </body>
</html>

CodePudding user response:

An svg element has a size, and your line is outside of the that area.

The default setting for an svg is:

svg:not(:root) {
    overflow: hidden;
}

so your line won't be visible.

If you add this to your style:

svg {
  overflow: visible;
  border: 1px solid red;
}

You will see where your svg is located and its dimension, and overflow: visible; makes the line visible:

But instead of using overflow: visible; you should change the size and/or positioning of the svg.

  • Related