Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I draw a line using jQuery?

I have a web app where I would like the user to draw a line in the following way: When he clicks on Point1 and he moves the mouse, draw the line from Point1 to the current mouse position and, when clicks to Point2 draw the final line from Point1 to Point2.

How can I do it using jQuery and/or one of its plugins?

like image 932
Cris Avatar asked Jul 31 '12 15:07

Cris


People also ask

How do you add a new line in jQuery?

You have to use <br> to have line breaks. You can replace line breaks to <br> just for display.

What does $() mean in jQuery?

In jQuery, the $ sign is just an alias to jQuery() , then an alias for a function. This page reports: Basic syntax is: $(selector).action() A dollar sign to define jQuery.


2 Answers

Challenge accepted.

I tried to do it with CSS transforms and a bunch of Math in Javascript - after half an hour I have this:

http://jsfiddle.net/VnDrb/2/

Make 2 clicks into the gray square and a line should be drawn. There is still a small bug that draws the line wrong when the angle is > 45 degree. Maybe someone else knows how to fix that. Maybe instead of using Math.asin (arcsinus), use a other trigonometrical function, but I'm really not good at it. I thought I'd post it even there is a small bug, I think it's a good start for you.

like image 159
Jonny Burger Avatar answered Oct 01 '22 08:10

Jonny Burger


I've tried a number of different approaches this weekend and the solution that worked best for me is from Adam Sanderson: http://monkeyandcrow.com/blog/drawing_lines_with_css3/

His demo is here: http://monkeyandcrow.com/samples/css_lines/

The core of it is very simple, which is always good.

div.line{
  transform-origin: 0 100%;
  height: 3px; /* Line width of 3 */
  background: #000; /* Black fill */
}


function createLine(x1,y1, x2,y2){
  var length = Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
  var angle  = Math.atan2(y2 - y1, x2 - x1) * 180 / Math.PI;
  var transform = 'rotate('+angle+'deg)';

    var line = $('<div>')
      .appendTo('#page')
      .addClass('line')
      .css({
        'position': 'absolute',
        'transform': transform
      })
      .width(length)
      .offset({left: x1, top: y1});

  return line;
}
like image 22
BaronGrivet Avatar answered Oct 01 '22 08:10

BaronGrivet