简体   繁体   中英

How to connect the dots ? (the dots are randomly positioned HTML elements)

I'm using the following code to generate random points with a maximum distance from another element I have in the page:

function drawPoints (maxdistance, npoints) {
  var start = $('#startingPoint').position();
  var draw = document.getElementById('draw');

  var i = npoints;
  while(i--) {
    var n = document.createElement('div');
    n.style.position = 'absolute';
    n.style.top = ( - (Math.random() * maxdistance) -10 + start.top).toString() + 'px';
    n.style.left = ( - (Math.random() * maxdistance) + 50 + start.left).toString() + 'px';
    n.style.width = '6px';
    n.style.height = '6px';
    n.style.backgroundColor = 'black';
    n.style.borderRadius = '6px';
    draw.appendChild(n);
  }
}

For an example, drawPoints(150, 20); would draw 20 points with a maximum distance of 150 from the starting point.

The question is, how do I draw some kind of arcs or lines to connect some of this dots ?

Using the canvas and other new features is very good, but I think that almost ALL things can be re-programmed with very simple built-in functions (and of course without jQuery).

This is a cross-browser function to connect the dots:

function connectDots(xA,yA,xB,yB)
{
    var a=document.createElement("div");
    var r=180*Math.atan2(yB-yA,xB-xA)/Math.PI;
    a.setAttribute("style","width:"+Math.sqrt(Math.pow(xA-xB,2)+Math.pow(yA-yB,2))+"px;height:1px;position:absolute;background-color:black;top:"+yA+"px;left:"+xA+"px;-moz-transform:rotate("+r+"deg);-moz-transform-origin:0px 0px;-webkit-transform:rotate("+r+"deg);-webkit-transform-origin:0px 0px;transform:rotate("+r+"deg);transform-origin:0px 0px;-ms-transform:rotate("+r+"deg);-ms-transform-origin:0px 0px;");
    document.body.appendChild(a);
}

Four lines.

Fiddle: http://jsfiddle.net/mageek/3aG5H/2/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM