Solved

Draw a line Dynamically

Posted on 2003-11-20
9
645 Views
Last Modified: 2006-11-17
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
0
Comment
Question by:Sometimes
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
9 Comments
 
LVL 10

Accepted Solution

by:
NetGroove earned 168 total points
ID: 9786755
0
 
LVL 6

Assisted Solution

by:Webmonkey
Webmonkey earned 166 total points
ID: 9789659
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
 
LVL 2

Author Comment

by:Sometimes
ID: 9795601
Thanks webmoney but not all my users have IE6 any other ideas?
0
Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

 
LVL 6

Expert Comment

by:Webmonkey
ID: 9796113
How are you drawing a line now?  Please post that code.

WM
0
 
LVL 2

Author Comment

by:Sometimes
ID: 9797048
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
 
LVL 6

Expert Comment

by:Webmonkey
ID: 9799987
Ok.  I'll parse through this code and integrate the two to make it work.  I'll get back with you soon.

Webmonkey
0
 
LVL 2

Assisted Solution

by:alberthendriks
alberthendriks earned 166 total points
ID: 9845472
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
 
LVL 16

Expert Comment

by:jaysolomon
ID: 10383162
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

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

734 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question