Line/Curve between blocks

by Noir Noir

HTML

<svg id="plate"></svg>
<div class="block one"></div>
<div class="block two"></div>

SCSS

.block {
  position: relative;
  width: 100px;
  height: 100px;
  background: #000;
  border-radius: 10px;
  
  &.two {
    margin: 100px 0 0 300px
  }
}

#plate{
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
}

line,
path{
  stroke-width:2px;
  stroke:rgb(100,100,100);
}

path {
  stroke:rgb(100, 200, 0);
}

JavaScript

var plate = $('#plate');
var div1 = $('.block.one');
var div2 = $('.block.two');

var PATH = {
	move : function(elem, x, y) {
  	PATH.appendPath(elem, 'M '+x+','+y);
  },
  
  line : function(elem, x, y) {
  	PATH.appendPath(elem, 'L '+x+','+y);
  },
  
  curve: function(elem, x, y, xbx, xby, ybx, yby) {
  	PATH.appendPath(elem, 'C '+xbx+','+xby+' '+ybx+','+yby+' '+x+','+y);
  },
  
  appendPath: function(elem, string) {
  	var value = elem.getAttribute('d') || '';
    if (value) {
    	value += ' ';
    }
  	elem.setAttribute('d', value + string);
  }
};

function drawLine(plate, src, dst) {
	var tpl = '<line class="line"/>',
  	  line = document.createElementNS('http://www.w3.org/2000/svg','line');
  
  var x1 = src.offset().left + (src.width()/2);
  var y1 = src.offset().top + (src.height()/2);
  var x2 = dst.offset().left + (dst.width()/2);
  var y2 = dst.offset().top + (dst.height()/2);
  
  line.setAttribute('x1', x1);
  line.setAttribute('y1', y1);
  line.setAttribute('x2', x2);
  line.setAttribute('y2', y2);
  
  plate.append(line);
}

function drawCurve(plate, src, dst, blen) {
	var tpl = '<line class="line"/>',
      curve = document.createElementNS('http://www.w3.org/2000/svg','path');
  
  var x1 = src.offset().left + (src.width()/2);
  var y1 = src.offset().top + (src.height()/2);
  var x2 = dst.offset().left + (dst.width()/2);
  var y2 = dst.offset().top + (dst.height()/2);
  var sin = getSin(x1, y1, x2, y2);
  var cos = getCos(x1, y1, x2, y2);
  
  blen = blen || getGipo(x1, y1, x2, y2) / 5;
  
  curve.setAttribute('fill', 'none');
  PATH.move(curve, x1, y1);
  PATH.curve(
  	curve, 
    x2, y2,
    x1+sin*blen, y1-cos*blen,
    x2+sin*blen, y2-cos*blen
  );
  
  plate.append(curve);
  
  function getCos(x1, y1, x2, y2) {
  	var x = x2-x1;
        
    return x / getGipo(x1, y1, x2, y2);
  }
  
  function getSin(x1, y1, x2, y2) {
 		var y = y2-y1;
        
    return y / getGipo(x1, y1, x2, y2);
  }
  
  function getGipo(x1, y1, x2, y2) {
  	var x...