9

Hi i'm looking for drag step for each drag item, let say 200px

below image is demonstrating it:

enter image description here

i have searched a lot but did not find any solution related to that.

Question: The imaginary drag box step should be set to 200px, in other words it should jump to 200px

Full view codepen: https://codepen.io/eabangalore/pen/GaPzJw?editors=1000

Below snippet is not working please see codepen above

<!--
  Copyright (c) 2006-2013, JGraph Ltd
  
  Dynamic toolbar example for mxGraph. This example demonstrates changing the
  state of the toolbar at runtime.
-->
<html>
<head>
 <title>Toolbar example for mxGraph</title>

 <!-- Sets the basepath for the library if not in same directory -->
  <script type="text/javascript">
    mxBasePath = 'https://jgraph.github.io/mxgraph/javascript/src';
    
    
    
   function setGraphData(){
      var graphState = {"tagName":"mxGraphModel","children":[{"tagName":"root","children":[{"tagName":"mxCell","attributes":{"id":"0"}},{"tagName":"mxCell","attributes":{"id":"1","parent":"0"}},{"tagName":"mxCell","attributes":{"id":"2","style":"","vertex":"1","parent":"1"},"children":[{"tagName":"mxGeometry","attributes":{"x":"400","y":"130","width":"100","height":"40","as":"geometry"}}]},{"tagName":"mxCell","attributes":{"id":"3","style":"","vertex":"1","parent":"1"},"children":[{"tagName":"mxGeometry","attributes":{"x":"661","y":"101","width":"100","height":"40","as":"geometry"}}]}]}]};
      
      localStorage.setItem('graphState',JSON.stringify(graphState));
    }
    
     function html2json(html){
  if(html.nodeType==3){
   return {
    "tagName":"#text",
    "content":html.textContent
   }
  } 
  var element = {
   "tagName":html.tagName
  };

  if(html.getAttributeNames().length>0){
   element.attributes = html.getAttributeNames().reduce(
    function(acc,at){acc[at]=html.getAttribute(at); return acc;},
    {}
   );
  }

  if(html.childNodes.length>0){
   element.children = Array.from(html.childNodes)
    .filter(
     function(el){
      return el.nodeType!=3
      ||el.textContent.trim().length>0
     })
    .map(function(el){return html2json(el);});
  }
  return element;
 }

 function json2html(json){
  var xmlDoc = document.implementation.createDocument(null, json.tagName);

  var addAttributes = function(jsonNode, node){
   if(jsonNode.attributes){
    Object.keys(jsonNode.attributes).map(
     function(name){
      node.setAttribute(name,jsonNode.attributes[name]);
     }
    );
   }
  }

  var addChildren = function(jsonNode,node){
   if(jsonNode.children){
    jsonNode.children.map(
     function(jsonChildNode){
      json2htmlNode(jsonChildNode,node);
     }
    );
   }
  }

  var json2htmlNode = function(jsonNode,parent){
   if(jsonNode.tagName=="#text"){
    return xmlDoc.createTextNode(jsonNode.content);
   }

   var node = xmlDoc.createElement(jsonNode.tagName);

   addAttributes(jsonNode,node);
   addChildren(jsonNode,node);

   parent.appendChild(node);
  }

  addAttributes(json,xmlDoc.firstElementChild);
  addChildren(json,xmlDoc.firstElementChild);

  return xmlDoc;
 }
  </script>

  <!-- Loads and initializes the library -->
  <script type="text/javascript" src="https://jgraph.github.io/mxgraph/javascript/src/js/mxClient.js"></script>

 <!-- Example code -->
 <script type="text/javascript">
  // Program starts here. Creates a sample graph in the
  // DOM node with the specified ID. This function is invoked
  // from the onLoad event handler of the document (see below).
  function main()
  {
      
            setGraphData();
   // Checks if browser is supported
   if (!mxClient.isBrowserSupported())
   {
    // Displays an error message if the browser is
    // not supported.
    mxUtils.error('Browser is not supported!', 200, false);
   }
   else
   {
    // Defines an icon for creating new connections in the connection handler.
    // This will automatically disable the highlighting of the source vertex.
    mxConnectionHandler.prototype.connectImage = new mxImage('images/connector.gif', 16, 16);

    // Creates the div for the toolbar
    var tbContainer = document.createElement('div');
    tbContainer.style.position = 'absolute';
    tbContainer.style.overflow = 'hidden';
    tbContainer.style.padding = '2px';
    tbContainer.style.left = '0px';
    tbContainer.style.top = '0px';
    tbContainer.style.width = '24px';
    tbContainer.style.bottom = '0px';
    
    document.body.appendChild(tbContainer);
   
    // Creates new toolbar without event processing
    var toolbar = new mxToolbar(tbContainer);
    toolbar.enabled = false
    
    // Creates the div for the graph
    var container = document.createElement('div');
    container.style.position = 'absolute';
    container.style.overflow = 'hidden';
    container.style.left = '24px';
    container.style.top = '0px';
    container.style.right = '0px';
    container.style.bottom = '0px';
    container.style.background = 'url("editors/images/grid.gif")';

    document.body.appendChild(container);
    
    // Workaround for Internet Explorer ignoring certain styles
    if (mxClient.IS_QUIRKS)
    {
     document.body.style.overflow = 'hidden';
     new mxDivResizer(tbContainer);
     new mxDivResizer(container);
    }
 
    // Creates the model and the graph inside the container
    // using the fastest rendering available on the browser
    var model = new mxGraphModel();
    var graph = new mxGraph(container, model);

    // Enables new connections in the graph
    graph.setConnectable(true);
    graph.setMultigraph(false);

    // Stops editing on enter or escape keypress
    var keyHandler = new mxKeyHandler(graph);
    var rubberband = new mxRubberband(graph);
    
    var addVertex = function(icon, w, h, style)
    {
     var vertex = new mxCell(null, new mxGeometry(0, 0, w, h), style);
     vertex.setVertex(true);
    
     var img = addToolbarItem(graph, toolbar, vertex, icon);
     img.enabled = true;
     
     graph.getSelectionModel().addListener(mxEvent.CHANGE, function()
     {
      var tmp = graph.isSelectionEmpty();
      mxUtils.setOpacity(img, (tmp) ? 100 : 20);
      img.enabled = tmp;
     });
    };
    
    addVertex('https://jgraph.github.io/mxgraph/javascript/examples/editors/images/rectangle.gif', 100, 40, '');
    addVertex('https://jgraph.github.io/mxgraph/javascript/examples/editors/images/rounded.gif', 100, 40, 'shape=rounded');
    addVertex('https://jgraph.github.io/mxgraph/javascript/examples/editors/images/ellipse.gif', 40, 40, 'shape=ellipse');
    addVertex('https://jgraph.github.io/mxgraph/javascript/examples/editors/images/rhombus.gif', 40, 40, 'shape=rhombus');
    addVertex('https://jgraph.github.io/mxgraph/javascript/examples/editors/images/triangle.gif', 40, 40, 'shape=triangle');
    addVertex('https://jgraph.github.io/mxgraph/javascript/examples/editors/images/cylinder.gif', 40, 40, 'shape=cylinder');
    addVertex('https://jgraph.github.io/mxgraph/javascript/examples/editors/images/actor.gif', 30, 40, 'shape=actor');
        
        
           // read state on load 
    if(window.localStorage.graphState){ 
     var doc = json2html(JSON.parse(localStorage.graphState)); 
     var dec = new mxCodec(doc);
     dec.decode(doc.documentElement, graph.getModel());
    }

    // save state on change
    graph.getModel().addListener('change',function(){
      var codec = new mxCodec();  
      window.localStorage.graphState = JSON.stringify(html2json(codec.encode(
       graph.getModel()
      )));
    });
   }
  }

  function addToolbarItem(graph, toolbar, prototype, image)
  {
   // Function that is executed when the image is dropped on
   // the graph. The cell argument points to the cell under
   // the mousepointer if there is one.
   var funct = function(graph, evt, cell, x, y)
   {
    graph.stopEditing(false);

    var vertex = graph.getModel().cloneCell(prototype);
    vertex.geometry.x = x;
    vertex.geometry.y = y;
     
    graph.addCell(vertex);
    graph.setSelectionCell(vertex);
   }
   
   // Creates the image which is used as the drag icon (preview)
   var img = toolbar.addMode(null, image, function(evt, cell)
   {
    var pt = this.graph.getPointForEvent(evt);
    funct(graph, evt, cell, pt.x, pt.y);
   });
   
   // Disables dragging if element is disabled. This is a workaround
   // for wrong event order in IE. Following is a dummy listener that
   // is invoked as the last listener in IE.
   mxEvent.addListener(img, 'mousedown', function(evt)
   {
    // do nothing
   });
   
   // This listener is always called first before any other listener
   // in all browsers.
   mxEvent.addListener(img, 'mousedown', function(evt)
   {
    if (img.enabled == false)
    {
     mxEvent.consume(evt);
    }
   });
      
   mxUtils.makeDraggable(img, graph, funct);
   
   return img;
  }

 </script>
</head>

<!-- Calls the main function after the page has loaded. Container is dynamically created. -->
<body onload="main();" >

</body>
</html>
Parth Pandya
  • 1,050
  • 7
  • 15
  • 22
EaBengaluru
  • 131
  • 2
  • 17
  • 59

2 Answers2

3

Changed how value is set to the graph state:

function generateData(x1, y1, x2, y2){
  var graphState = {"tagName":"mxGraphModel","children":[{"tagName":"root","children":[{"tagName":"mxCell","attributes":{"id":"0"}},{"tagName":"mxCell","attributes":{"id":"1","parent":"0"}},{"tagName":"mxCell","attributes":{"id":"2","style":"","vertex":"1","parent":"1"},"children":[{"tagName":"mxGeometry","attributes":{"x": x1,"y": y1 ,"width":"100","height":"40","as":"geometry"}}]},{"tagName":"mxCell","attributes":{"id":"3","style":"","vertex":"1","parent":"1"},"children":[{"tagName":"mxGeometry","attributes":{"x": x2,"y": y2,"width":"100","height":"40","as":"geometry"}}]}]}]};
  return graphState;
}


function setGraphData(){
  var graphState = generateData("400", "130", "661", "101");
  localStorage.setItem('graphState',JSON.stringify(graphState));
} 

Refresh the data after page load:

if(window.localStorage.graphState){ 
        var doc = json2html(JSON.parse(localStorage.graphState));
        var dec = new mxCodec(doc);
        dec.decode(doc.documentElement, graph.getModel());

    setTimeout(function() {
        var doc = json2html(generateData("400", "30", "661", "101"));
        var dec = new mxCodec(doc);
        dec.decode(doc.documentElement, graph.getModel());
     }, 5000);
}

This will move the box up after a gap of 5 seconds.

CodePen

Maverick
  • 791
  • 9
  • 23
  • your **solution** does not solve my **problem**, please see image i posted for this question. **my question:** if i drag box it should jump `200px` on the same `Axis`. – EaBengaluru Jun 11 '19 at 16:27
  • please edit your solution to reflect my question. please help me thanks in advance!! – EaBengaluru Jun 11 '19 at 16:38
0

in order to solve this situation, you need to update the mouseMove function in the mxgraphhandler class. I created a codepen example with the solution.

Code Pen Solution

Updated mouseMove function

mxGraphHandler.prototype.mouseMove = function (sender, me) {
var graph = this.graph;
if (!me.isConsumed() && graph.isMouseDown && this.cell != null &&
    this.first != null && this.bounds != null && !this.suspended) {
    if (mxEvent.isMultiTouchEvent(me.getEvent())) {
        this.reset();
        return;
    }
    var delta = this.getDelta(me);
    var tol = graph.tolerance;
    if (this.shape != null || this.livePreviewActive || Math.abs(delta.x) > tol || Math.abs(delta.y) > tol) {
        if (this.highlight == null) {
            this.highlight = new mxCellHighlight(this.graph,
                mxConstants.DROP_TARGET_COLOR, 3);
        }

        var clone = graph.isCloneEvent(me.getEvent()) && graph.isCellsCloneable() && this.isCloneEnabled();
        var gridEnabled = graph.isGridEnabledEvent(me.getEvent());
        var cell = me.getCell();
        var hideGuide = true;
        var target = null;
        this.cloning = clone;

        if (graph.isDropEnabled() && this.highlightEnabled) {
            target = graph.getDropTarget(this.cells, me.getEvent(), cell, clone);
        }

        var state = graph.getView().getState(target);
        var highlight = false;

        if (state != null && (clone || this.isValidDropTarget(target, me))) {
            if (this.target != target) {
                this.target = target;
                this.setHighlightColor(mxConstants.DROP_TARGET_COLOR);
            }

            highlight = true;
        }
        else {
            this.target = null;

            if (this.connectOnDrop && cell != null && this.cells.length == 1 &&
                graph.getModel().isVertex(cell) && graph.isCellConnectable(cell)) {
                state = graph.getView().getState(cell);

                if (state != null) {
                    var error = graph.getEdgeValidationError(null, this.cell, cell);
                    var color = (error == null) ?
                        mxConstants.VALID_COLOR :
                        mxConstants.INVALID_CONNECT_TARGET_COLOR;
                    this.setHighlightColor(color);
                    highlight = true;
                }
            }
        }

        if (state != null && highlight) {
            this.highlight.highlight(state);
        }
        else {
            this.highlight.hide();
        }

        if (this.guide != null && this.useGuidesForEvent(me)) {
            delta = this.guide.move(this.bounds, delta, gridEnabled, clone);
            hideGuide = false;
        }
        else {
            delta = this.graph.snapDelta(delta, this.bounds, !gridEnabled, false, false);
        }

        if (this.guide != null && hideGuide) {
            this.guide.hide();
        }

        if (graph.isConstrainedEvent(me.getEvent())) {
            if (Math.abs(delta.x) > Math.abs(delta.y)) {
                delta.y = 0;
            }
            else {
                delta.x = 0;
            }
        }

        this.checkPreview();
        // Update start
        const diffX = this.currentDx - delta.x;
        const diffY = this.currentDy - delta.y;
        if (diffX >= moveX) {
            this.currentDx += -moveX;
            this.currentDy = this.currentDy ? this.currentDy : 0;
            this.updatePreview();
        } else if (diffX <= -moveX) {
            this.currentDx += moveX;
            this.currentDy = this.currentDy ? this.currentDy : 0;
            this.updatePreview();
        }

        if (diffY >= moveY) {
            this.currentDy += -moveY;
            this.currentDx = this.currentDx ? this.currentDx : 0;
            this.updatePreview();
        } else if (diffY <= -moveY) {
            this.currentDy += moveY;
            this.currentDx = this.currentDx ? this.currentDx : 0;
            this.updatePreview();
        }

    }
    // Update end

    this.updateHint(me);
    this.consumeMouseEvent(mxEvent.MOUSE_MOVE, me);

    mxEvent.consume(me.getEvent());
}
else if ((this.isMoveEnabled() || this.isCloneEnabled()) && this.updateCursor && !me.isConsumed() &&
    (me.getState() != null || me.sourceState != null) && !graph.isMouseDown) {
    var cursor = graph.getCursorForMouseEvent(me);

    if (cursor == null && graph.isEnabled() && graph.isCellMovable(me.getCell())) {
        if (graph.getModel().isEdge(me.getCell())) {
            cursor = mxConstants.CURSOR_MOVABLE_EDGE;
        }
        else {
            cursor = mxConstants.CURSOR_MOVABLE_VERTEX;
        }
    }

    if (cursor != null && me.sourceState != null) {
        me.sourceState.setCursor(cursor);
    }
}

};