1

I have a table element with numbers from 1 to 100, and I want to programmatically add lines between any two cells using CSS. In order to do that, I created an absolute-positioned div. Now I should use the offsets of the cells to calculate the position, the height and the rotation degree for that div.

Let's make s the "start point" cell's offset and e the "end point" cell's offset.

  • I figured that the div's offset should be like s's.
  • Based on the Pythagorean theorem, I figured that the height should be Math.sqrt( Math.pow(s.top-e.top, 2) + Math.pow(s.left-e.left, 2) ).
  • Using trigonometry, I figured that the rotation degree should be -Math.atan2(s.top-e.top, s.left-e.left)*180/Math.PI.

Some (or all) of these are probably wrong, because I tried them and it doesn't seem to produce the correct line. Here's a fiddle for demonstration. Can anyone correct me so that this algorythm will produce the correct line?

Thanks!

hillai
  • 93
  • 7
  • This should answer your question: http://stackoverflow.com/questions/18012420/draw-diagonal-lines-in-div-background-with-css – intrepidis Mar 10 '15 at 20:21
  • @ChrisNash The thing is I want to make this kind of lines stretch between two td elements. – hillai Mar 10 '15 at 20:25
  • 1
    http://jsbin.com/lipuxarifi/ I added `transform-origin` – blex Mar 10 '15 at 20:33
  • Yeah, just position the top left of the div to where the start of the line should go and the bottom right for the end of the line. In this day and age you shouldn't need to work out the basic trig of a diagonal line. Just let the css styling work that out for you. – intrepidis Mar 10 '15 at 20:55

1 Answers1

0

Position the top left of the div to where the start of the line should go and the bottom right of the div to the end of the line.

The div will look something like this:

<div class="diag" style="top: 0px; right: 100px; bottom: 300px; left: 0px;"></div>

Then use an SVG image in CSS like this:

.diag {
    background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' preserveAspectRatio='none' viewBox='0 0 100 100'><path d='M1 0 L0 1 L99 100 L100 99' fill='black' /></svg>");
    background-repeat:no-repeat;
    background-position:center center;
    background-size: 100% 100%, auto;
    position: absolute;
}

Take a look here to see it visually:

.diag {
  background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' preserveAspectRatio='none' viewBox='0 0 100 100'><path d='M1 0 L0 1 L99 100 L100 99' fill='black' /></svg>");
  background-repeat: no-repeat;
  background-position: center center;
  background-size: 100% 100%, auto;
  position: absolute;
}
<div class="diag" style="top: 0px; right: 100px; bottom: 300px; left: 0px;"></div>
Goran Stoyanov
  • 2,311
  • 1
  • 21
  • 31
intrepidis
  • 2,870
  • 1
  • 34
  • 36