Is there any way to write with jQuery
in html
. Hence when a user click any one of the shown image, a line between them will be appeared. I found a lot of info about " how to do it in canvas",and I found it is possible to just use the images in html
file.
For example when clicked on id1 and the id4 a line appears that connects them.
Asked
Active
Viewed 1,600 times
-2

Sandesh
- 1,190
- 3
- 23
- 41

user3095198
- 83
- 10
-
Can you put a separator image in between and make it visible on any of image click? – MysticMagicϡ Dec 12 '13 at 11:48
-
1Something like this: http://jsfiddle.net/kDs2Q/45/? – TheCarver Dec 12 '13 at 11:51
-
Possible duplicate of [Drawing a line between two divs](https://stackoverflow.com/questions/6278152/drawing-a-line-between-two-divs) – balupton Nov 05 '18 at 21:03
2 Answers
0
This won't work in IE8 or below due to CSS restrictions. It uses pure Javascript, no need for jQuery.
function getOffset( el ) { // return element top, left, width, height
var _x = 0;
var _y = 0;
var _w = el.offsetWidth|0;
var _h = el.offsetHeight|0;
while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
_x += el.offsetLeft - el.scrollLeft;
_y += el.offsetTop - el.scrollTop;
el = el.offsetParent;
}
return { top: _y, left: _x, width: _w, height: _h };
}
function connect(div1, div2, color, thickness) { // draw a line connecting elements
var off1 = getOffset(div1);
var off2 = getOffset(div2);
// bottom right
var x1 = off1.left + off1.width;
var y1 = off1.top + off1.height;
// top right
var x2 = off2.left + off2.width;
var y2 = off2.top;
// distance
var length = Math.sqrt(((x2-x1) * (x2-x1)) + ((y2-y1) * (y2-y1)));
// center
var cx = ((x1 + x2) / 2) - (length / 2);
var cy = ((y1 + y2) / 2) - (thickness / 2);
// angle
var angle = Math.atan2((y1-y2),(x1-x2))*(180/Math.PI);
// make hr
var htmlLine = "<div style='padding:0px; margin:0px; height:" + thickness + "px; background-color:" + color + "; line-height:1px; position:absolute; left:" + cx + "px; top:" + cy + "px; width:" + length + "px; -moz-transform:rotate(" + angle + "deg); -webkit-transform:rotate(" + angle + "deg); -o-transform:rotate(" + angle + "deg); -ms-transform:rotate(" + angle + "deg); transform:rotate(" + angle + "deg);' />";
//
// alert(htmlLine);
document.body.innerHTML += htmlLine;
}
Simply call it by using something like:
<a onclick="testIt();">Draw line</a>
window.testIt = function() {
var div1 = document.getElementById('div1');
var div2 = document.getElementById('div2')
connect(div1, div2, "#0F0", 2);
}