Motyar

@motyar

Freelance Web Developer

Static Web Hosting, made easy

Feb 20, 2010

Draw rectangle with Jquery

After reading my previous post about drawing with jquery, someone asked me about drawing rectangle with jquery. Here in this post i am trying to disclose the way we can draw rectangle with jquery.





It is simple, i am listing here some steps -

Determine the position of rectangle
We will draw with mouse-drag event, so have to record the position onmousedown. we assume that is the point(x1,y1).

Define the size of rectangle
Suppose we drag mouse from point(x1,y1) to point(x2,y2) so the size of rectangle will be (x2-x1)X(y2-y1) i.e height X width. We will capture the point(x2,y2) onmouseup

Code

<script type="text/javascript"> 
$(document).ready(function() {
  var x1,x2,y1,y2;
  $(document).mousedown(function(e) {
    $(&quot;
  #current&quot;
  ).attr({ id''
   })
    box = $('&lt;
  div style=&quot;
  border:1px #FF00FF solid;
  position:fixed;
  &quot;
  &gt;
  ').hide();
    $(document.body).append(box);
    x1 e.pageX;
    y1 e.pageY;
    box.attr({id'current'}).css({
             tope.pageY //offsets
             lefte.pageX //offsets
   }).fadeIn();
  });
  $(document).mousemove(function(e) {
    $(&quot;
  #current&quot;
  ).css({
      width:Math.abs(e.pageX x1), //offsets
      height:Math.abs(e.pageY y1//offsets
   }).fadeIn();
  });
  $(document).mouseup(function() {
    $(&quot;
  #current&quot;
  ).attr({ id''
   })
  });
 
 </script>

Demo



You can see this code in action here. Drag to draw a rectangle.

Related post

Draw with jquery

Labels:




By :