简体   繁体   中英

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?

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.

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM