gen
gen

Reputation: 10040

how can I position objects in raphael.js related to center

When I set x, y values to objects to position them on the paper, it measures x, y from the top left corner. Is there any way to change it so that it would position related to the center middle of the paper?

Upvotes: 1

Views: 1799

Answers (2)

Tuan Chau
Tuan Chau

Reputation: 1333

Raphael does not support g element. So, you can run an loop and add attribute transform="translate(*half_of_canvas_width*, *half_of_canvas_height*)" like this:

var paper = new Raphael("canvas");

var cx = 250;
var cy = 250;

var rec = paper.rect(0, 0, 250, 250).attr({fill:'red'})

var list = document.getElementById("canvas").childNodes[0].childNodes;
for(var i = 2 /*because the first two elements are desc tag*/, l = list.length; i < l; i++){
    list[i].setAttribute("transform", "translate(250,250)");
}

demo:

http://jsfiddle.net/ry8kT/150/

Good luck :)

Upvotes: 1

Brian
Brian

Reputation: 5028

Raphael has rectangles, circles, and ellipses.

  • Latter 2 are positioned with center coordinates, so you have nothing to worry about.
  • Rectangle is positioned based on its top left corner coordinates

So to answer to your question:

Raphael does not exactly provide a way to position the rectangle with center coordinates.
However you can do that by yourself easily.
Look at this DEMO.

For example:

// lets assume your center coordinates are cx and cy
var rec = paper.rect(cx, cy, 120, 80);

// to position in the middle, just do this
var rec = paper.rect(cx - 120/2, cy - 80/2, 120, 80);

It is as simple as that. Good luck!


Edit

If that is what you want to do in your project, then just Raphael.js and override the rectangle class.

Upvotes: 1

Related Questions