Motyar

@motyar

Freelance Web Developer

Static Web Hosting, made easy

Jan 14, 2010

Draw with jquery

UPDATE - You must check the Drawing on web with canvas and JQuery

In this post I want to explain " How to Draw with jquery on web page? like msPaint brush". I had implemented this just for fun!
There are a lot of good plugins of jquery to draw basic geometric shapes like rectangles, circles etc.


But i found no one that allow me to draw as we draw in msPaint (or other drawing tools). I tried to implement this.

The idea

I started with a simple logic - to draw colored elements(spans) following mouse location on mousemove. Then used a flag to implement it with mouse drag, flag=true(on mousedown) and flas=false(on mouseup).

Code


The Javascript

 $(document).ready(function() {
 var draw false;

 //set it true on mousedown
 $(document).mousedown(function(){draw=true;});

 //reset it on mouseup
 $(document).mouseup(function(){draw=false;});


 $(document).mousemove(function(e) {

    //if mouse is down
    if(draw==true){

                //make a pixel (5X5) at mouse position
                pointer = $('<span>').css({
                                                'position':'absolute',
                                                'background-color':'#ff00ff',
                                                'width':'5px',
                                                'height':'5px',
                                                tope.pageY ,    //offsets
                                                lefte.pageX   //offsets
                                           });

                //append it to body
                $(document.body).append(pointer);
        }
    });
});

 


Demo

Its time to a test drive. Open the demo and drag your mouse.
You can see it in action here.

UPDATE - You must check the Drawing on web with canvas and JQuery


Labels: , , ,




By :