2010-06-01

Flechas con RaphaelJS

Me encontré con que no hay ningún método para dibujar flechas en raphaelJS, así que me puse las pilas y programé uno:

 /**
* Returns a path in form of an arrow
* @param arrowSize is the size of the arrow end. Defaults to 10 pixels.
*/
Raphael.fn.arrow = function(x1, y1, x2, y2, arrowSize) {
var arrowSize = arrowSize || 10
var l = Math.sqrt( Math.pow( x2 - x1, 2 ) + Math.pow( y2 - y1, 2 ) )
var xStep = (x2 - x1) / l
var yStep = (y2 - y1) / l

// arrow point ends
var arrX1 = x2 + arrowSize * (yStep - xStep) / 2
var arrY1 = y2 + arrowSize * (-xStep - yStep) / 2
var arrX2 = x2 + arrowSize * (-yStep - xStep) / 2
var arrY2 = y2 + arrowSize * (xStep - yStep) / 2

var path = ["M", x1, y1, "L", x2, y2, //main line
"M", arrX1, arrY1, "L", x2, y2, "L", arrX2, arrY2] //arrow end

return this.path(path.join(" "))
}

Para usarlo hay que hacer:

var r = Raphael(....)
.....
var arrow = r.arrow(150,100,250,300)