Centering/zooming view to a specific element

Hi

I would like to know is there is a possibility to center a viewer to a specific element - so that element that I have (its ID), will be presented in the middle/center of a window/page or a place where viewer is created. I found out this post

But I guess it have not been implemented, right? I tried this approach:

		var elementRegistry = viewer.get('elementRegistry');
		var element = elementRegistry.get(id);
		canvas.zoom(0, {
			x : element.x,
			y : element.y
		});

and nothing happens in the viewer. I also tried to increase the number 0 to e.g. 3,4,5…and its get zoomed, but for sure the center is not my element… Behaves really strange. Does anyone knows what is the best practice to center to a specific element ? I have a very large bpmn diagram and I want to make the one that is highlighted to be presented in the middle, and maybe wit a little zoom. Centering is the most important…

thanks

Searching for elements via Ctrl+F centers viewbox just like that. So I think that you can just try to use _centerViewbox function from diagram-js/lib/features/search-pad/SearchPad.js.

var searchPad = viewer.get('search-pad');
searchPad._centerViewbox(element);

N.B. I didn’t test this code snippet.

You better copy the code found in SearchPad#_centerViewbox though. It is private API that may change or be removed any time.

Thank you guys, I figured out some other solution, seems much easier then the one provided in _centerVIewport. But thanks anyway!

BTW I think that the current zoom method should be improved somehow, because it just does not do what is described in API. It is really misleading

What solution did you find?

1 Like

A simple solution for centering a given element, keeping the zoom level as-is is:

function centerElement(elementId) {
  // assuming we center on a shape.
  // for connections we must compute the bounding box
  // based on the connection's waypoints
  var bbox = elementRegistry.get(elementId);

  var currentViewbox = canvas.viewbox();

  var elementMid = {
    x: bbox.x + bbox.width / 2,
    y: bbox.y + bbox.height / 2
  };

  canvas.viewbox({
    x: elementMid.x - currentViewbox.width / 2,
    y: elementMid.y - currentViewbox.height / 2,
    width: currentViewbox.width,
    height: currentViewbox.height
  });
}