简体   繁体   中英

Set the origin of element to center instead of top left (jquery)

I have this marker (which is a simple div) inside the triangle: 三角形和标记

The center of the marker should lie exactly in the centroid of the triangle.

As seen in the picture, it's not exactly in the centroid (it's a bit to the right, and possible to the bottom).

I'm using jquery ui .draggable method. Here is my css for the marker:

#marker {
  position: absolute;
  background: #808080;
  border-radius: 50%;
  width: 50px;
  height: 50px;
  cursor: grab;
}

And here's my jquery script:

$(document).ready(function () {
  var triangle = $("#triangle");
  var marker = $("#marker");
  var coord = getTriangleCoordinates(triangle);
  var center = centroid(coord);

  $("#marker").hover(
    function () {
      // over
      $(this).css("filter", "brightness(0.8)");
    },
    function () {
      // out
      $(this).css("filter", "brightness(1)");
    }
  );

  $("#marker").mouseup(function () {
    $(this).css("background", "salmon");
  });

  $("#marker").draggable({
    drag: function (event, ui) {
      var offset = ui.offset;
      if (!bounded(offset, coord)) return false;
    }
  });

  marker.css("left", Math.round(center.left) - 5 + "px");
  marker.css("top", Math.round(center.top) - 5 + "px");

  console.log(coord);
});

How do I make the default position of the marker's center exactly in the centroid, while still being able to drag the marker?

I tried the transform: translate(-50%, 0) css property. Although it fixed the position, it messed up the dragging feature altogether.

Any help is appreciated. Thanks!!

Your marker element has width 50px and height 50px.

Assuming your centroid function returns the correct result, you are then positioning the top left corner of the marker (remember, it is basically a square) at a mere 5px offset from the actual centroid.

It needs to be offset by half its width and height so that its central point is at the centroid.

So change this:

  marker.css("left", Math.round(center.left) - 5 + "px");
  marker.css("top", Math.round(center.top) - 5 + "px");

To this:

  marker.css("left", Math.round(center.left) - 25 + "px");
  marker.css("top", Math.round(center.top) - 25 + "px");

For a more general solution, if for example the dimensions of the marker might change with viewport size or something, you can set the top left to the centroid and then transform: translate(-50%, 50%) . This will move the marker left and up by half its own width and height, whatever they are.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM