Raphael Javascript Library Tips and Tricks

I’ve started learning the Raphael 2D drawing library for JavaScript. I’ll use this post to store any useful tips and tricks I pick up along the way. Hopefully this will help save others the time it takes to figure out certain things.

Place a Raphael Canvas in a Div

To attach a Raphael canvas to a div, create div first and then create a Raphael object which references the ID of the div. You can make the canvas fill the div by setting its width and height to 100%. E.g.:

<div class="canvas" id="canvas1"></div>
<script>
var paper = Raphael("canvas1", "100%", "100%");
</script>

Chain Attributes

With Raphael you can chain attributes, like so:

paper.circle(100,100,10)
     .attr("fill","#f00")
     .attr("stroke","#fff");

This lets you style simple objects without the need to store the object in a variable first.

Draw a Line

The syntax for drawing a line isn’t totally intuitive. To draw a line from (160,70) to (540,70) do:

var line = paper.path("M 160 70 L 540 70");

To draw a relative line change the L to a lowercase l. Doing so in the example above will draw a line from (160,70) to (160+540, 70+70).

Drawing a Dotted / Dashed Line

To make a line dotted, do:

line.attr("stroke-dasharray",". ");

To make a line dashed, do:

line.attr("stroke-dasharray","- ");

Make Elements Draggable

Suppose you have elements p1…p5 which you wish to make draggable. You can do it like so:

// make points draggable
var start = function () {
  this.ox = this.attr("cx");
  this.oy = this.attr("cy");
},
move = function (dx, dy) {
  this.attr({cx: this.ox + dx, cy: this.oy + dy});
},
up = function () {};
paper.set(p1,p2,p3,p4,p5).drag(move, start, up);

Auto-updating Connecting Lines

Sometimes you want to have a line connecting two objects which is updated automatically when those objects move. This can be done using the connect() function given in this StackOverflow answer. Here’s an example of it in action.

Comments

Share your thoughts