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>
2
Answers
In this code, we first calculate the offsets of the click coordinates relative to the container and the image. These offsets are then used to adjust the marker’s position within the container.
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 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.