How to update the lines so that they do not break away from the rectangles after dragging?

To add to what Kirupa was saying…
If you created a way of having groups you could update all items in the group on drag. So drag by the rectangle and then update all other items by the same offset. Then you could add a circle (can be invisible if you want) as the point where the line starts/ends. Then have another object/list that keeps track of what points join up with other points and then draw the lines appropriately. Im not sure how the drag is working right now so cant make an example just yet and have to go out in a sec but might make something when I get back coz svg is something I really want to learn.
Oh and I had a quick look at grouping in svg…its a pain. “g” doesnt have x y cords and cant automatically drag things together (such a shame). One person used the idea of adding an svg element that can, here, that seems like a kinda good way of doing it. Or your going to have to implement something yourself, which wouldnt be to bad…thats why I added the data-group attribute.

But now to what really got my interest. Why are you using innerHTML to get stuff done? Why not use the dom when theres so much there to use, its prolly more performant, etc. Like I said, I still have to learn this stuff but I had a quick look around and made this…


    // Creates and mods an svg elements attributes
    function svgElement(element, attributes) {
      if (typeof element == 'string') element = document.createElementNS('http://www.w3.org/2000/svg', element);
      for (prop in attributes) {
        element.setAttribute(prop, attributes[prop])
      }
      return element;
    }

      var rec = svgElement('rect', {
      width: 200,
      height: 80,
      x: 400,
      y: 50,
      class: 'draggable',
      fill: 'red',
      stroke: 'green',
      id: 'ivan',
      "data-group": "one"
    });

    var circle1 = svgElement('circle', {
      cx: rec.x.baseVal.value + rec.width.baseVal.value / 2,
      cy: rec.y.baseVal.value + rec.height.baseVal.value,
      r: 10,
      "data-group": "one"
    });

    forDraw.appendChild(rec);
    forDraw.appendChild(circle1);

This will add the first rectangle and the point where the line starts. Am I doing it the right/best way, no idea, got lots more to learn myself.
Like I said Ill prolly add more to this when I get back.

EDIT: Oh, and the best advice I can give you is to use a library. Theres a few around and they have already gone through all this pain and worked out all the problems. But then if your trying to really learn SVG then I totally get it.

1 Like