Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 16
  1. #1
    ubh
    ubh is offline
    Regular Coder ubh's Avatar
    Join Date
    Apr 2008
    Location
    Portland, Oregon U.S.A.
    Posts
    443
    Thanks
    108
    Thanked 15 Times in 14 Posts

    Simple Box Drawing

    Ok I have a need to be able to click, drag and create a div box on my document.

    Is it not true that if I was able to capture my mouses coordinates at all times I could then preform a snap shot of what the coordinates are upon clicking on the document?

    Is is not true that I could also at the same time create a div and set to be absolute while setting top left to this captured mouse coordinate?

    Also once the div box is created, begin to record the mouse coordinates only upon moving the mouse and still clicking.

    Is it not true that I could from these two coordinates find the area in width and height that I have drawn with my mouse and feed to this newly created div box these width and height values?

    If so great! I have done all the math in finding my mouse coordinates. I figured out how to capture the mouse coordinates upon onclick.
    I figured out how to record the coordinates upon still being clicked and mouse being moved to then even calculate the resulting in this with and height area values for the div box.

    I just cant figure out how I would feed these width and height values to this div box dynamically and live like I need. Can anyone please help me I am kinda stuck.

    Please have a look at my demo page.
    http://www.devinrolsen.com/help/divCreator/index.html

    PS:sorry for the messy code.

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,602
    Thanks
    78
    Thanked 4,387 Times in 4,352 Posts
    This isn't quite right, because it starts showing the box even before the mouse button goes down. But that's pretty minor fix.

    For starters, add a <div> *directly* after the <body> tag, thus:
    Code:
    <body onload="load('x','y')" onmousedown="capture('onX','onY'); load('offX','offY');" onmouseup="load('x','y')">
    <div id="BOX" style="position: absolute; display: none; border: solid red 2px; background-color: pink;"></div>
    And then here is your revised function. It does *NOT* handle boxes drawn from right to left or bottom to top. Could easily be fixed, but let's start somewhere.
    Code:
    function getMouseCoordinates(event)
    {
    	var bx = document.getElementById("BOX");
    	var ev = event || window.event;
    	var mse=zxcMse(ev);
    
    	xObj.value = mse[0];
    	yObj.value = mse[1];
    
    	var xa = document.getElementById("onX").value;
    	var xb = document.getElementById("offX").value;
    	var w = xb - xa;
            if ( w < 0 ) w = 0;
    	document.getElementById("width").value = w;
    	
    	var ya = document.getElementById("onY").value;
    	var yb = document.getElementById("offY").value;
    
            var h = yb - ya;
            if ( h < 0 ) h = 0;
    	document.getElementById("height").value = h;
            bx.style.left = xa;
            bx.style.top  = ya;
            bx.style.width = w;
            bx.style.height = h;
            bx.style.display = "block";
            		
    }
    Last edited by Old Pedant; 03-17-2009 at 06:30 AM.

  • #3
    Regular Coder
    Join Date
    Mar 2009
    Location
    Portland Oregon
    Posts
    690
    Thanks
    44
    Thanked 63 Times in 62 Posts
    I was playing with your script last week and I recall you were feeding it width and height equal to zero. I switched it and got it to draw, but I couldn't follow what you were doing with the booleans so I tossed into the test bin for a look later on. I just opened it up and saw that I have it drawing a rectangle from 00 to pagex pagey

    I'm not sure why you do the boolean thing. I turned them off and the script at least draws. You want to make a loop I think and each time through you update the dimensions of the div instead of trying to do some true false thing. I'm assuming you're trying toget the div to draw as it's being made. You'll have to loop on the mousemove event probably.

    here's what I managed to get working.
    Code:
    <html>
    <head>
    
    <script type="text/javascript">
    document.onmousemove = getPosition;
    var divAlreadycreated = false;
    var divnotdone = true;
    var divWidthHeightcheck = false;
    var NewY, NewX, newdiv, x, y, newdivHeight, newdivWidth,startposx,startposy;
    
    function getPosition(e) 
        {
        e = e || window.event;
        var cursor = {x:0, y:0};
            if (e.pageX || e.pageY) {
              cursor.x = e.pageX;
              cursor.y = e.pageY;
            } 
            else {
              var de = document.documentElement;
              var b = document.body;
              cursor.x = e.clientX + 
                (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
                cursor.y = e.clientY + 
                  (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
            }
           
            x = cursor.x;
            y = cursor.y; 
            document.forms[0].MouseY.value = y;
            document.forms[0].MouseX.value = x;
    
        }
    
    
    function getHeightWidth(e) 
        {
            //if ( divWidthHeightcheck )
           // {
               // divnotdone = false;
    
    
           // }
          //  else
          //  {
                				//divWidthHeightcheck = true;
                var NewX = x;
                var NewY = y;
                document.forms[0].Width.value = NewX;
                document.forms[0].Height.value = NewY;
                createDiv(NewX,NewY);
           // }
        }
    
    function createDiv(NewX,NewY)
        {
            newdiv = document.createElement('div');
            var divIdName = 'testDiv';
            newdiv.setAttribute('id',divIdName);
            newdiv.style.width = NewX +'px';
            newdiv.style.height =NewY +'px';
            newdiv.style.left = NewX-startposx +'px';
            newdiv.style.top = NewY-startposy +'px';
            newdiv.style.position = 'absolute';
            newdiv.style.border = '1px solid #000';
            document.body.appendChild(newdiv); 
            divAlreadycreated = true;
        }
    
    function divMove()
        {
            					//if ( divAlreadycreated ){
              findingHeightWidth();
           									// }
        }
    
    function findingHeightWidth()
        {
     startposx=x;
    startposy=y;
    				//if ( divnotdone ){
    newdivHeight = y - NewY ;
    newdivWidth = x - NewX ;
      			
    if( newdivHeight < 0 ){
               newdiv.style.top = NewY+'px';
               newdiv.style.height = Math.abs( newdivHeight )+'px';
         			}
    else
    {
    newdiv.style.top = NewY+'px';
    newdiv.style.height = newdivHeight+'px';
    }
    
    
    
    if( newdivWidth < 0 )
        {
               newdiv.style.left = NewX+'px';
               newdiv.style.width = Math.abs( newdivWidth )+'px';
         }
    else
          {
    newdiv.style.left = NewX+'px';
    newdiv.style.width = newdivWidth+'px';
           }
     					//}/*if divnotdone*/
    
        
    }
    </script>
    
    </head>
    <body onmousemove="divMove();" onclick="getHeightWidth();"><form name"anyName">
    X: <input type="text" name="MouseX" size="4" readonly>
    Y: <input type="text" name="MouseY" size="4" readonly>
    X: <input type="text" name="Width" size="4" readonly>
    Y: <input type="text" name="Height" size="4" readonly>
    </form></body>
    
    </html>

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,602
    Thanks
    78
    Thanked 4,387 Times in 4,352 Posts
    Easy fix to the box appearing too soon: Change very last line there to this:
    Code:
            if ( w > 0 && h > 0 ) bx.style.display = "block";
    Not most elegant way. And you'll find some other fun things to fix. But...

  • #5
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,602
    Thanks
    78
    Thanked 4,387 Times in 4,352 Posts
    TinyScript: Why create the box on the fly instead of just resizing/positioning an existing <DIV>???

    Well, I guess if you wanted to be able to create dozens of boxes...

  • #6
    Regular Coder
    Join Date
    Mar 2009
    Location
    Portland Oregon
    Posts
    690
    Thanks
    44
    Thanked 63 Times in 62 Posts
    heheh I moved the function to draw the div into the mouse event and it works. Now your boolean makes sense. Try that in your script. You want the onmousedown and onmouseup instead of onclick to control the booleans

  • #7
    Regular Coder
    Join Date
    Mar 2009
    Location
    Portland Oregon
    Posts
    690
    Thanks
    44
    Thanked 63 Times in 62 Posts
    Yeah. I'm not entirely sure what the script is supposed to do, but I tried to make it do what I thought it was supposed to do.
    You guys are real coders, you should be able to sort out this mess... excuse me, messes. LOL

  • #8
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,602
    Thanks
    78
    Thanked 4,387 Times in 4,352 Posts
    Well, I was just looking for the quickest/dirtiest solution involving the fewest possible changes to his code. If I knew more what the purpose was, my answer might be different. So we each mess in our own separate ways. <grin/>

  • #9
    ubh
    ubh is offline
    Regular Coder ubh's Avatar
    Join Date
    Apr 2008
    Location
    Portland, Oregon U.S.A.
    Posts
    443
    Thanks
    108
    Thanked 15 Times in 14 Posts
    Wow got a bit of reply while my back was turned.

    The purpose of this script is a quicker way to build a layout with my home made CMS. Basically the CMS given a real state area to a user to build a site layout, they point click and draw their div boxes on the fly. Don't worry about the details beyond the scope of this thread lol I have it all worked out I just need help with the below.

    Ok so yes I do want div boxes created on the fly! However I want the div boxes created at the instant moment the mouse is clicked not released.

    Now I have been able to do this with out a problem, (not posted anywhere) but the real issue I have is I want this div box to have a width of 0px and height of 0px at the moment of it being created (mouse down).

    Then while the mouse is being held down and dragged the box will grow in width and height, live or rather in real time, until you have released the mouse click and its width and height are set.

    Not easy I know

  • #10
    ubh
    ubh is offline
    Regular Coder ubh's Avatar
    Join Date
    Apr 2008
    Location
    Portland, Oregon U.S.A.
    Posts
    443
    Thanks
    108
    Thanked 15 Times in 14 Posts
    OK I took another stab at it, I reverted back to my original code its going to need to be cleaned up again, but here is the basic idea of what I am trying to do minus the little glitches.

    http://www.devinrolsen.com/help/divCreator/index.html

    Click, drag top left to bottom right SLOWLY and you will see the effect I am trying to perfect with the div creation, I just dont know how to work out the bugs now.

    -Random re size of boxes when multiple are made
    -Box being created stops width and height manipulation if going to fast and mouse falls off div box.

    Any help is much appreciated guys thanks so much!

  • #11
    ubh
    ubh is offline
    Regular Coder ubh's Avatar
    Join Date
    Apr 2008
    Location
    Portland, Oregon U.S.A.
    Posts
    443
    Thanks
    108
    Thanked 15 Times in 14 Posts
    Ok I cleared up some of the problems and even got it to flip to re-size from left to right or right to left. I just cant get the top to bottom and bottom to top to work.

    Check it out.

    http://www.devinrolsen.com/help/divCreator/index.html

  • #12
    ubh
    ubh is offline
    Regular Coder ubh's Avatar
    Join Date
    Apr 2008
    Location
    Portland, Oregon U.S.A.
    Posts
    443
    Thanks
    108
    Thanked 15 Times in 14 Posts

    Unhappy Its Fine In FF But Wont work in IE ERRRR

    I spent more time on this script today and now I have it inverting and resizing from all sides YAY!

    http://www.devinrolsen.com/help/divCreator/index.html

    Down side is that you still have to move the mouse slowly in order to not break out of the box while its drawing...

    Next, the whole script fails to work in IE, and I cant seem to figure it out what might be causing it, but I think it might have something to do with DOM vs COM.

    On the topic of DOM vs COM I have up till now not set my document to any xhtml standards cause my body tag thus far is using onmousedown and onmouseup attributes in the body tag. Turning on xhtml will break these needed functions in the body tag so I don't know how I would "by standards" apply these attributes to the body tag.

    Anyone please if you could help me locate this error or at least give me a hint on being able to work this script to xhtml standard I would be forever grateful!!

  • #13
    Senior Coder
    Join Date
    Mar 2005
    Location
    Portsmouth UK
    Posts
    4,513
    Thanks
    3
    Thanked 504 Times in 491 Posts
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    
    <head>
      <title></title>
    <style type="text/css">
    /*<![CDATA[*/
    #canvas {
      position:relative;z-Index:2;left:50px;top:0px;width:800px;height:500px;border:solid black 1px;
    }
    
    .box {
      position:absolute;overflow:hidden;width:0px;height:0px;border:solid black 1px;
    }
    
    .drag {
      position:absolute;overflow:hidden;left:0px;top:0px;width:5px;height:5px;background-Color:red;cursor:move;
    }
    
    /*]]>*/
    </style>
    
    <script type="text/javascript">
    /*<![CDATA[*/
    // Make, ReSize, Drag Boxes (19-March-2009) DRAFT
    // by:  http://www.vicsjavascripts.org.uk
    
    
    function zxcBoxes(id,cls,dcls,did){
     var oop=new zxcBOOP(id,cls,dcls,did);
    
    }
    
    function zxcBOOP(id,cls,dcls,did){
     this.canvas=document.getElementById(id);
     zxcES(this.canvas,{cursor:'pointer'});
     this.box=zxcES('DIV',{});
     this.box.className=cls;
     if (dcls){
      var d=zxcES('DIV',{cursor:'move'},this.box);
      d.className=dcls;
     }
     this.addevt(this.canvas,'mousedown','newbox');
     this.addevt(this.canvas,'mousemove','msemove');
     this.addevt(this.canvas,'mouseup','mseup');
     this.nbox=false;
     this.reszbox=false;
     this.dragbox=false;
     this.dobj=document.getElementById(did)||false;
     this.ary=[];
    }
    
    zxcBOOP.prototype.newbox=function(evt){
     this.pos=this.mse(evt)
     this.cursor=this.canvas.style.cursor;
     var obj=window.event?evt.srcElement:evt.target;
     var docs=window.event?zxcDocS():[0,0];
     if (obj.style.cursor=='move'){
      var p=obj.parentNode
      this.dragbox=[p,zxcLTWH(p,'left'),zxcLTWH(p,'top'),zxcLTWH(p,'width'),zxcLTWH(p,'height')];
     }
     else if (this.cursor=='pointer') this.nbox=[zxcES(this.box.cloneNode(true),{left:this.pos[0]-docs[0]+'px',top:this.pos[1]-docs[1]+'px'},this.canvas),this.pos[0]-docs[0],this.pos[1]-docs[1]];
     return false;
    }
    
    zxcBOOP.prototype.msemove=function(evt){
     var pos=this.mse(evt);
     if (this.dragbox) this.drag(pos);
     else this.ckresize(pos);
     if (this.nbox){
      var docs=window.event?zxcDocS():[0,0];
      zxcES(this.nbox[0],{left:Math.min(this.pos[0],pos[0])+'px',top:(pos[1]<this.nbox[2]?pos[1]:this.nbox[2])+'px',width:Math.abs(this.pos[0]-pos[0])+'px',height:Math.abs(this.pos[1]-pos[1]-docs[1])+'px'});
     }
     else if (this.reszbox) this.resize(pos);
     return false;
    }
    
    zxcBOOP.prototype.mseup=function(){
     if (this.nbox){
      for (var add=true,z0=0;z0<this.ary.length;z0++){ if (this.ary[z0][0]==this.nbox[0]) add=false; }
      if (add) this.ary.push([this.nbox[0]]);
     }
     for (var z1=0;z1<this.ary.length;z1++){
      if (zxcLTWH(this.ary[z1][0],'width')<6||zxcLTWH(this.ary[z1][0],'height')<6){
       this.canvas.removeChild(this.ary[z1][0]);
       this.ary.splice(z1,1);
       z1--;
      }
      if (this.ary[z1]) this.ary[z1][1]=[zxcLTWH(this.ary[z1][0],'left'),zxcLTWH(this.ary[z1][0],'top'),zxcLTWH(this.ary[z1][0],'width'),zxcLTWH(this.ary[z1][0],'height')];
     }
     this.reszbox=false;
     zxcES(this.canvas,{cursor:'pointer'});
     this.reszbox=false;
     this.dragbox=false;
     this.nbox=false;
     if (this.dobj) this.display();
    }
    
    zxcBOOP.prototype.ckresize=function(pos){
     var docs=window.event?zxcDocS():[0,0];
     pos[0]-=docs[0]; pos[1]-=docs[1];
     this.reszbox=false;
     zxcES(this.canvas,{cursor:'pointer'});
     for (var z0=0;z0<this.ary.length;z0++){
      var l=this.ary[z0][1][0],t=this.ary[z0][1][1],w=this.ary[z0][1][2],h=this.ary[z0][1][3];
      if (pos[1]>t+5&&pos[1]<t+h-5){
       if (pos[0]>l&&pos[0]<l+5) zxcES(this.canvas,{cursor:'w-resize'});
       else if (pos[0]>l+w-5&&pos[0]<l+w) zxcES(this.canvas,{cursor:'e-resize'});
      }
      else if (pos[0]>l+5&&pos[1]<l+w-5){
       if (pos[1]>t&&pos[1]<t+5) zxcES(this.canvas,{cursor:'n-resize'});
       else if (pos[1]>t+h-5&&pos[1]<t+h) zxcES(this.canvas,{cursor:'s-resize'});
      }
      if (this.cursor!='pointer'){
       if (!this.boxwh) this.boxwh=[l,t,w,h];
       return this.reszbox=this.ary[z0];
      }
     }
    }
    
    zxcBOOP.prototype.resize=function(pos){
     if (this.reszbox){
      if (this.cursor=='e-resize'&&pos[0]>this.reszbox[1][0]) zxcES(this.reszbox[0],{width:Math.max(Math.abs(this.reszbox[1][0]-pos[0]),0)+'px'});
      else if (this.cursor=='w-resize'&&pos[0]<this.reszbox[1][0]) zxcES(this.reszbox[0],{left:pos[0]+'px',width:this.reszbox[1][2]+this.reszbox[1][0]-pos[0]+'px'});
      else if (this.cursor=='s-resize'&&pos[1]>this.reszbox[1][1]) zxcES(this.reszbox[0],{height:Math.max(Math.abs(this.reszbox[1][1]-pos[1]),0)+'px'});
      else if (this.cursor=='n-resize'&&pos[1]<this.reszbox[1][1]) zxcES(this.reszbox[0],{top:pos[1]+'px',height:this.reszbox[1][3]+this.reszbox[1][1]-pos[1]+'px'});
     }
    }
    
    zxcBOOP.prototype.drag=function(pos){
     zxcES(this.dragbox[0],{left:Math.min(Math.max(this.dragbox[1]+pos[0]-this.pos[0],0),this.canvas.offsetWidth-this.dragbox[3])+'px',top:Math.min(Math.max(this.dragbox[2]+pos[1]-this.pos[1],0),this.canvas.offsetHeight-this.dragbox[4])+'px'});
     return false;
    }
    
    zxcBOOP.prototype.display=function(pos){
     this.dobj.value=this.ary.join('\n');
    }
    
    zxcBOOP.prototype.addevt=function(o,t,f,p){
     var oop=this;
     if (o.addEventListener) o.addEventListener(t,function(e){ return oop[f](e,p);}, false);
     else if (o.attachEvent) o.attachEvent('on'+t,function(e){ return oop[f](e,p); });
     else {
      var prev=o['on'+t];
      if (prev) o['on'+t]=function(e){ prev(e); oop[f](e,p); };
      else o['on'+t]=o[f];
     }
    }
    
    zxcBOOP.prototype.mse=function(evt){
     var pos=zxcPos(this.canvas);
     if (document.all) return [evt.clientX+zxcDocS()[0]-pos[0],evt.clientY+zxcDocS()[1]-pos[1]];
     return [evt.pageX-pos[0],evt.pageY-pos[1]];
    }
    
    function zxcDocS(){
     if (!document.body.scrollTop) return [document.documentElement.scrollLeft,document.documentElement.scrollTop];
     return [document.body.scrollLeft,document.body.scrollTop];
    }
    
    function zxcPos(obj){
     var rtn=[obj.offsetLeft,obj.offsetTop];
     while(obj.offsetParent!=null){
      var objp=obj.offsetParent;
      rtn[0]+=objp.offsetLeft-objp.scrollLeft;
      rtn[1]+=objp.offsetTop-objp.scrollTop;
      obj=objp;
     }
     return rtn;
    }
    
    function zxcES(ele,style,par,txt){
     if (typeof(ele)=='string') ele=document.createElement(ele);
     for (key in style) ele.style[key]=style[key];
     if (par) par.appendChild(ele);
     if (txt) ele.appendChild(document.createTextNode(txt));
     return ele;
    }
    
    function zxcLTWH(obj,par){
     if (obj.currentStyle) return parseInt(obj.currentStyle[par]);
     return parseInt(document.defaultView.getComputedStyle(obj,null).getPropertyValue(par));
    }
    
    
    
    /*]]>*/
    </script>
    
    
    
    </head>
    
    <body onload="zxcBoxes('canvas','box','drag','display');" >
    <div id="canvas" ></div>
    <div style="height:2000px;" ></div>
    <textarea id="display" rows="10" cols="50" ></textarea>
    </body>
    
    </html>
    Last edited by vwphillips; 03-19-2009 at 05:56 PM.
    Vic

    God Loves You and will never love you less.

    http://www.vicsjavascripts.org/Home.htm

    If my post has been useful please donate to http://www.operationsmile.org.uk/

  • #14
    ubh
    ubh is offline
    Regular Coder ubh's Avatar
    Join Date
    Apr 2008
    Location
    Portland, Oregon U.S.A.
    Posts
    443
    Thanks
    108
    Thanked 15 Times in 14 Posts
    DUDE vwphillips! This is simply amazing! I cant really read any of it, far to advanced for me but seriously man thanks!!

  • #15
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,602
    Thanks
    78
    Thanked 4,387 Times in 4,352 Posts
    UBH: You have an AWESOME site there! Your rounded corners trick, alone, is worth the price of admiission! (I've been doing it with...naw, you wouldn't want to see it. It's too ugly. hint: 8 nested divs)


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •