Draw a line Dynamically

I need to draw a line on a html page, it should draw from the point the user clicks and drag out to the point the mouse is. In other words the end of the line should follow the current mouse location.

I have done it with a rectangle  and can draw a line on a page but not dynamically


thanks
LVL 2
SometimesAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Experts Exchange Solution brought to you by ConnectWise

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
 
WebmonkeyCommented:
Ok, I've got something good here for you.  I'm not sure if you are restricted to JavaScript or not, but this example does what you want using VML (Vector Markup Language).  Now, realize that VML only works in IE 6+.  Since this might not be what you want, if you have the ability to draw lines some other way, you could easily transpose this code to fit your needs.

Also, the positioning is a little off, but I'm still working on it.  I igured I'd go ahead and post what I've got so you can see it.

Webmonkey
---------------------------------------------------
<html xmlns:v="urn:schemas-microsoft-com:vml">

<head>
<style>
v\:* { behavior:url(#default#VML); }
</style>
</head>

<body>
<form name="form1">
X <input type=text name=x id=x value="<unknown>"><br>
Y <input type=text name=y id=y value="<unknown>">
</form>

<br><br>

<v:line name="myLine" id="myLine" from="0pt, 0pt" to="0pt, 0pt" strokecolor="red" strokeweight="2pt" style="position:absolute;">

<script type=text/javascript>

      var isIE = document.all?true:false;
      if (!isIE) document.captureEvents(Event.MOUSEUP);
      document.onmouseup = markStartPoint;

      function markStartPoint(e) {
        var _x;
        var _y;
        if (!isIE) {
          _x = e.pageX;
          _y = e.pageY;
        }
        if (isIE) {
          _x = event.clientX + document.body.scrollLeft;
          _y = event.clientY + document.body.scrollTop;
        }

        document.form1.x.value=_x;
        document.form1.y.value=_y;
        
        myLine.from = _x + "pt, " + _y;

        document.form1.x.value=_x;
        document.form1.y.value=_y;

        followMouse();
        
        return true;
      }

      function followMouse() {
            var isIE = document.all?true:false;
            if (!isIE) document.captureEvents(Event.MOUSEMOVE);
            document.onmousemove = markEndPoint;
      }


      function markEndPoint(e) {
        var _x;
        var _y;
        if (!isIE) {
          _x = e.pageX;
          _y = e.pageY;
        }
        if (isIE) {
          _x = event.clientX + document.body.scrollLeft;
          _y = event.clientY + document.body.scrollTop;
        }

        document.form1.x.value=_x;
        document.form1.y.value=_y;
        
        myLine.to = _x + "pt, " + _y;
        
        return true;
      }
</script>


</body>
</html>
0
 
SometimesAuthor Commented:
Thanks webmoney but not all my users have IE6 any other ideas?
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

 
WebmonkeyCommented:
How are you drawing a line now?  Please post that code.

WM
0
 
SometimesAuthor Commented:
Here is the line codes

call line line(a,b,c,d,5)

for example

<SCRIPT LANGUAGE="JavaScript">
var line = function(x1,y1,x2,y2,inc) {
     var distx = x2 - x1;
     var disty = y2 - y1;
     var N = Math.floor(Math.sqrt(distx*distx + disty*disty)/inc);
     var a = getNormalizedAngle(x1,y1,x2,y2);
     var dx = inc * Math.cos(a);
     var dy = -inc * Math.sin(a);
     var path = [];
     for (var i=0;i<=N;i++) {
          path[i*2] = Math.round(x1 +  i*dx);
          path[i*2+1] = Math.round(y1 + i*dy);
     }
     if (path[i*2-2] != x2 || path[i*2-1] != y2) {
          path[i*2] = x2;
          path[i*2+1] = y2;
     }
     j=0;
     xcor=[],ycor=[];
     for(i=0; i<path.length; i+=2)
     {
          xcor[j]=path[i];
          ycor[j]=path[i+1];
          j++;
     }
     for(i=0; i<xcor.length; ++i){
 

    document.body.innerHTML+="<div id='yes' style=\"position:absolute;width:3px;height"
     +":3px;clip:rect(0,2,2,0);left:"+xcor[i]+"px;top:"+ycor[i]+"px;background-color:#111111"
     +"\">.<\/div>"
     
     }
};
getNormalizedAngle = function(x1,y1,x2,y2) {
     var distx = Math.abs(x1-x2);
     var disty = Math.abs(y1-y2);
     if (distx==0 && disty==0) angle = 0;
     else if (distx==0) angle = Math.PI/2;
     else angle = Math.atan(disty/distx);
     if (x1<x2) {
          if (y1<y2) angle = Math.PI*2-angle;
     }
     else {
          if (y1<y2) angle = Math.PI+angle;
          else angle = Math.PI-angle;
     }
     return angle;
};




This is the dynamic rectangle which works fine makediv()

var cnt=0, drag=false, x, y, ol, ot, nw, nh, nw2, nh2, w, h, l, t;

function makediv(){
      cnt+=1; ol=-1; drag=true;
      document.body.innerHTML+="<div id='b"+cnt+"' style='font-size:0px; color: white; position: absolute; background-color: transparent; border:red 1px dotted; left: "+x+"; top: "+y+"'></div>"
      return
}

function dragdiv(){
      if(ol<0){ol=x;ot=y;}
            obj=document.getElementById('b'+cnt).style;
            l=obj.left.split('px').join('')*1; t=obj.top.split('px').join('')*1;
            obj=document.getElementById('b'+cnt).style;
            nw=x-l; nh=y-t; if(nw<0){nw=-nw;}if(nh<0){nh=-nh;}
            w=obj.width.split('px').join('')*1; h=obj.height.split('px').join('')*1;
            nw2=l+w-x; nh2=t+h-y; if(nw2<0){nw2=0;}if(nh2<0){nh2=0;}
            window.status=w+','+h;
             if(x<=l){obj.width=w+nw;}if(y<=t){obj.height=h+nh;}
             if(x<=ol){obj.left=x;obj.width=nw2;}
             else{obj.width=nw;}
             if(y<=ot){obj.top=y;obj.height=nh2;}
             else{obj.height=nh;}
}

function chkDrag(e){
      if (document.all) {
            x=event.x+document.body.scrollLeft; y=event.y+document.body.scrollTop;}
       else{
             x=e.pageX;y=e.pageY;if(x<0){x=0;}if(y<0){y=0;}}
      if(drag){dragdiv();}
}
      document.onmousemove=chkDrag;
      var exit=true;


</script>

hope this helps
0
 
WebmonkeyCommented:
Ok.  I'll parse through this code and integrate the two to make it work.  I'll get back with you soon.

Webmonkey
0
 
alberthendriksCommented:
The way I dot it is resizing an image or replacing its src attribute when resizing ****s up the line. The resulting line is still not very beautiful. An example can be found at
http://www.alberthendriks.com/dop/gba/map.php?id=1&mode=1
(Press the "nieuw" button and start clicking on the image)
should work in mozilla, IE5+ NS5+.

It uses image.php:

<?php
Header("Content-Type: image/png");

$pi = 3.14159265;

$red = $_REQUEST["red"];
$green = $_REQUEST["green"];
$blue = $_REQUEST["blue"];
$thickness = $_REQUEST["thickness"];
$angle = $_REQUEST["angle"];
$length = $_REQUEST["length"];
if($length=="") $length=25;

if($angle==180 OR $angle==-180 OR $angle==0) {
  $im = ImageCreate($length,$thickness);
  $color = ImageColorAllocate($im,$red,$green,$blue);

  ImagePNG($im);
}
else if($angle==90 OR $angle==270 OR $angle==-90 OR $angle==-270) {
  $im = ImageCreate($thickness,$length);
  $x=1;
  $y=$length;
  $white = ImageColorAllocate($im, 255, 255, 255);
  imageColorTransparent($im,$white);

  $color = ImageColorAllocate($im,$red,$green,$blue);

  imagesetthickness($im,$thickness+2);
  imageLine($im,$x/2,0,$x/2,$y,$color);
  ImagePNG($im);
}
else {

  $x = round($length*cos($pi*$angle/180));
  $y = round($length*sin($pi*$angle/180));
  if($x>=0) $x++; else $x--;
  if($y>=0) $y++; else $y--;

  $im = ImageCreate(abs($x),abs($y));

  $white = ImageColorAllocate($im, 255, 255, 255);
  imageColorTransparent($im,$white);

  $color = ImageColorAllocate($im,$red,$green,$blue);

  imagesetthickness($im,$thickness);

  if($x*$y>=0) {
    imageLine($im,0,abs($y),abs($x),0,$color);
  }
  else {
    imageLine($im,0,0,abs($x),abs($y),$color);
  }
  ImagePNG($im);
}

?>

and transp_img.php:

<?php
Header("Content-Type: image/png");

$width= $_REQUEST["width"];
$height = $_REQUEST["height"];

$im = ImageCreate($width,$height);
$white = ImageColorAllocate($im, 255, 255, 255);
imageColorTransparent($im,$white);
ImagePNG($im);
?>
0
 
jaysolomonCommented:
No comment has been added lately, so it's time to clean up this TA.
I will leave the following recommendation for this question in the Cleanup topic area:

Split: NetGroove {http:#9786755} & Webmonkey {http:#9789659} & alberthendriks {http:#9845472}

Please leave any comments here within the next four days.
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

jAy
EE Cleanup Volunteer
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.