Is there a way to draw shape (Rectangle) using Raphael like this?
http://devfiles.myopera.com/articles/649/example3.html
I tried below code but it didn’t do the trick because the rectangle shape appears only after ((onmouseup)) Event
Unlike the desired example above with mouse click and hold, on which the shape starts as a point, the size of the shape then changes as the user moves the mouse until the user releases the mouse the shape becomes permanent
$("#div1").mousedown(function(e) {
var offset = $("#div1").offset();
mouseDownX = e.pageX - offset.left;
mouseDownY = e.pageY - offset.top;
});
$("#div1").mouseup(function(e) {
var offset = $("#div1").offset();
var upX = e.pageX - offset.left;
var upY = e.pageY - offset.top;
var width = upX - mouseDownX;
var height = upY - mouseDownY;
DrawRectangle(mouseDownX, mouseDownY, width, height);
});
function DrawRectangle(x, y, w, h) {
var element = paper.rect(x, y, w, h);
element.attr({
fill : "gray",
opacity : .5,
stroke : "#F00"
});
$(element.node).attr('id', 'rct' + x + y);
element.drag(move, start, up);
element.click(function(e) {
elemClicked = $(element.node).attr('id');
});
}
Full example available in this fiddle
http://jsfiddle.net/XMyHz/26/
Here’s an example that uses Raphael to recreate the drawing example you linked to:
http://jsfiddle.net/4Kdhz/1/
As @Neil mentioned, you need to change the dimensions of the shape when you move the mouse, so the basic flow is this:
onmousedown:onmousemovethat executes a drawing function,doDraw().onmouseup:onmousemovelistener.doDraw():onmousedowncoordinates.Note that with Raphael, a rectangle can’t have a negative width or height, hence changing the starting coordinates and multiplying the width and height by -1.