I'm looking for Javascript code for letting the user draw a line (on an image).
Just as the line tool in Photoshop (for example):
The user clicks on the image, drags the mouse (while the line between the start point and the mouse point is dynamically drawn on mouse drag).
I would also need a callable function to send the page the start and end coordinates.
I've found this very nice script for area selection: http://www.defusion.org.uk/code/javascript-image-cropper-ui-using-prototype-scriptaculous/
and I've found many script for drawing lines (and other shapes in JS), but could not find what I'm looking for.
Thanks
Since there is no standard method of drawing, if you want to support older browsers and IE,
you will need to use a library. The library will handle the cross platform issues of drawing with SVG
or Microsoft's VML
I recommend Raphael JS
raphael.js is a lightweight rendering tool for javascript (MIT licensed) which works in FF, Safari, Chrome and IE6+.
It uses SVG for the first 3 and VML for IE but the API is identical across browsers and very sweet.
http://raphaeljs.com/
e.g.
// Creates canvas 320 × 200 at 10, 50
var paper = Raphael(10, 50, 320, 200);
// Creates circle at x = 50, y = 40, with radius 10
var circle = paper.circle(50, 40, 10);
// Sets the fill attribute of the circle to red (#f00)
circle.attr("fill", "#f00");
// Sets the stroke attribute of the circle to white
circle.attr("stroke", "#fff");
I've used it to draw a line while dragging and can vouch for its ease of use
A cross-browser solution for drawing lines in javascript, without requiring any external libraries, can be found here: http://bytes.com/topic/javascript/answers/88771-drawing-vector-lines-javascript
This works in all browsers, including IE.
Consider using the canvas
element to display the image. Then, drawing a line (or anything else) on it is trivial.
If your maths is good enough, it is possible (although mad) to do it without the canvas tag for most modern browsers using one of (as appropriate):
By creating eg. a 1px high div, with eg. a border-top for your 'line', and using the mouse drag event to position and rotate it.
Madness lies this way but it would be a quite fun exercise. (You should use something like Raphael JS, which is cross browser and sane - see above)
i'm working on something similar. Drawing a line on a canvas is pretty simple. You can take from my code here.
http://p-func.com/html5_test/test2.html
Just follow the mousedown listener.
Although I have found, when wanting to load images, that the raphael library might be better to use. I saw this because Canvas seems to act like a flat image. So if I want to add an aimge to it, then allow the user to manipulate that image, it won't let me (unless there is something that i am missing).
Raphael allows you to draw and still use those drawings, and images, as objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With