z-index layering in raphael.js

1.5k views Asked by At

I'm using Raphael to draw different shapes in different layers. I'd like to implement CSS z-index layering so that no matter which function is executed first(draw_rect, draw_circle or draw_line), the rectangle stays at the bottommost layer, the line, in the middle and the circle at the topmost layer. Here's what I've tried:

draw_rect(10, 10, 180, 180); 
draw_circle(100, 100, 60);
draw_line();
function draw_rect(x, y, width, height) {
  var rect = paper.rect(x, y, width, height);
  rect.attr({
    fill: 'red',
    position: 'absolute',
    'z-index': 1
  });
}
function draw_circle(x, y, radius) {
  var circ = paper.circle(x, y, radius);
  circ.attr({
    fill: 'green',
    position: 'absolute',
    'z-index': 3
  });
}
function draw_line() {
  var line = paper.path("M0,0L200,200");
  line.attr({
    'stroke': 'blue',
    position: 'absolute',
    'z-index': 2
  });
}

I can't use element.tofront() & element.toback() since the expressions bring the elements to the top/bottom layers only (not the middle layer). So, if somebody could enlighten me on doing the z-index layering, I'd be thankful for eternity :D

2

There are 2 answers

7
Ian On

Afaik you can't do this with z-index, unless you separate them into separate svg containers maybe (eg overlaying papers), as the SVG spec uses ordering to decide position.

Also there is no z-index 'attribute', its a style, so would need to be set via CSS (ie on the SVG container).

Otherwise you will have to do it via DOM ordering. You can possibly use something like el.insertBefore()/After() to help position them into the correct place, but that may need you to include a bit of extra logic. Eg you could place each one in a set and check them as you go, or use a selectAll statement to see if previous ones have been drawn, so you can add them before/after.

1
cms On

You can use line.toFront() to move the required layer to the front.