jhylands

Create a line in javascipt

Jan 12th, 2013
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 5 1.47 KB | None | 0 0
  1. <head>
  2. <style type="text/css">
  3.         .line
  4.     {
  5.             position: absolute;
  6.             height: 0px;
  7.         border-width: 2px 0px 0px 0px;
  8.         border-style: solid;
  9.         border-color: #99aadd;
  10.         }
  11. </style>
  12. <script type="text/javascript">
  13.         var isIE = navigator.userAgent.indexOf("MSIE") > -1;
  14.         window.onload = init;
  15.         function createLine(x1, y1, x2, y2)
  16.     {
  17.         if (x2 < x1)
  18.         {
  19.             var temp = x1;
  20.                 x1 = x2;
  21.                     x2 = temp;
  22.                 temp = y1;
  23.                     y1 = y2;
  24.                 y2 = temp;
  25.             }
  26.             var line = document.createElement("div");
  27.             line.className = "line";
  28.             var length = Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
  29.             line.style.width = length + "px";
  30.                 if (isIE)
  31.             {
  32.                 line.style.top = (y2 > y1) ? y1 + "px" : y2 + "px";
  33.                 line.style.left = x1 + "px";
  34.                 var nCos = (x2-x1)/length;
  35.                     var nSin = (y2-y1)/length;
  36.                     line.style.filter = "progid:DXImageTransform.Microsoft.Matrix(sizingMethod='auto expand', M11=" + nCos + ", M12=" + -1*nSin + ", M21=" + nSin + ", M22=" + nCos + ")";
  37.                 }
  38.                 else
  39.                 {
  40.                     var angle = Math.atan((y2-y1)/(x2-x1));
  41.                     line.style.top = y1 + 0.5*length*Math.sin(angle) + "px";
  42.                     line.style.left = x1 - 0.5*length*(1 - Math.cos(angle)) + "px";
  43.                     line.style.MozTransform = line.style.WebkitTransform = line.style.OTransform= "rotate(" + angle + "rad)";
  44.                 }
  45.                 return line;
  46.             }
  47.  
  48.             function init()
  49.             {
  50.                 var demoElement = document.getElementById("demo");
  51.                 demoElement.appendChild(createLine(100, 100, 0, 0));
  52.             }
  53.         </script>
  54.     </head>
  55.  
  56.     <body>
  57.  
  58.  
  59.                 <div id="demo"></div>
  60.            
  61.     </body>
Advertisement
Add Comment
Please, Sign In to add comment