SVG Grips

There are multiple ways to modify SVG content interactively. Most users prefer to manipulate geometry with the mouse, even when it is not as exact as numerical parameter input.

  1. You can drag the grip with the mouse - right button pressed.
  2. The grip is changing it's color to green in dragging mode.
  3. Releasing the mouse button stops dragging.

Try it.

The implementation uses a single ECMAScript object Grips for managing the grips behavior.

  1. The object stores itself as a new property window.grips of the global window object.
  2. The grips are designed as a group <g> element in the SVG's <defs> section and referenced via <use> elements. So it is very easy to change the grip's shape.
  3. DOM-2 events are used here instead of attribute events.
  4. The grips are grouped. This SVG group <g id="gripsContainer"> then receives the grip's mouse events via event bubbeling.
  5. A callback function is called whenever a grip changes it's position.

Here is the code for the external file <Grips.js>.

   // == Grips object ==============================================
   function Grips(container, callback)
   {
      this.container = container;
      this.callback = callback;
      this.current = null;
      window.grips = this;
   }

   Grips.Pick = function Grips_Pick(evt)
   {
      window.grips.current = evt.getTarget();
      window.grips.current.setAttribute("class", "pickedGrip");
      window.grips.container.addEventListener("mouseup", Grips.HandleEvent, false);
      window.grips.container.addEventListener("mousemove", Grips.HandleEvent, false);
      Grips.HandleEvent(evt);
   }

   Grips.HandleEvent = function Grips_HandleEvent(evt)
   {
      if (window.grips.callback) 
         window.grips.callback(window.grips.current, evt.getType(), evt.getClientX(), evt.getClientY());

      if (evt.getType() == "mouseup") // release grip ..
      {
         window.grips.current.setAttribute("class", "grip");
         window.grips.container.removeEventListener("mouseup", Grips.HandleEvent, false);
         window.grips.container.removeEventListener("mousemove", Grips.HandleEvent, false);
         window.grips.current = null;
      }
   }
   // === end ======================================================

An application Fourbar (4-Bar Linkage) demonstrates the use of the grips.

  1. The Fourbar consists of three independent lines lnk1, lnk2, lnk3 that are connected to each other in the points A, B.
  2. The Fourbar is also implemented as an ECMAScript object Fourbar.
  3. The Fourbar object implements the GripHandler method, that is handed over to the Grips object as the callback function.

There is still a lot to improve. So use this code as a starting point for your own solution.


© 2000 MecXpert