Unable to place the marker on exact mouse click area on the image

44 Views Asked by At

I am trying to place the marker on an image where the mouse clicks happen, but somehow my current code places the marker far from a mouse pointer which I don't understand as both the marker position and the mouse click coordinates are in px.

Does someone have any idea about this?

$scope.obj = {};
$scope.obj.myStyle = {};
$scope.img = function(event) {
  var x = event.clientX;
  var y = event.clientY;
  var coords = "X coords: " + x + ", Y coords: " + y;
  $log.info("coords--" + coords);
  $scope.obj.myStyle["left"] = event.clientX + 'px';
  $scope.obj.myStyle["top"] = event.clientY + 'px';
  $log.info($scope.obj.myStyle);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div id="myDiv" ng-click="img($event)">
  <img width="50%" height="50%" src="http://placekitten.com/g/400/300" alt="">
  <img style="width:20px;position: absolute;" ng-style="obj.myStyle" ng-if="obj.myStyle != {}" src="https://cdn1.iconfinder.com/data/icons/Map-Markers-Icons-Demo-PNG/128/Map-Marker-Marker-Outside-Chartreuse.png" id="marker" />

</div>

1

There are 1 best solutions below

0
Diego D On

In the most basic way and without involving Angular at all, just for the sake of showing how to interact with the DOM, this could be the easiest solution to achieve that goal:

//the marker element
const marker = document.getElementById('marker');

//for each element having the class 'can-be-pinned'
[...document.getElementsByClassName('can-be-pinned')]
  .forEach(el => {        
    //adds the click event handler, that will...
    el.addEventListener('click', event=>{      
      //change the position of the marker according to the mouse coords
      marker.style.left =  `${event.clientX}px`;
      marker.style.top =  `${event.clientY}px`;            
    });        
  })
#marker{
  position: absolute;
  width:20px;  
  border: solid 1px red;
}

.can-be-pinned{
  width: 50%;
  height: 50%;
}
<div id="myDiv">
  <img class="can-be-pinned" src="http://placekitten.com/g/400/300" alt="">  
</div>

<img
    id="marker"     
    src="https://cdn1.iconfinder.com/data/icons/Map-Markers-Icons-Demo-PNG/128/Map-Marker-Marker-Outside-Chartreuse.png"
 >

The marker is placed at the exact coords where the mouse has been clicked. I added a red border surrounding the marker to better show that behaviour. If you wished those coords to match with the exact center of the marker, you needed to compute its coords by subtracting its width/2 and height/2.