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


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


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

Related post

Draw with jquery


By :