MATLAB: How to continuously track / record coordinates of the cursor over an axes in the figure window

callbackcursorMATLABmotionmousewindow

I have a figure containing an axes and text box:
f = figure;
ax = axes(f,'Units','normalized','Position',[.1 .3 .8 .6]);
txt = annotation(f,'textbox','FontSize',12,...
'Units','normalized','Position',[.1 .1 .35 .06],...
'BackgroundColor','white');
How do I continuously track the location of the cursor and record it in the text box? And how do I make the tracking stop when the user clicks a certain button?

Best Answer

To continuously track/record the position of the user's cursor, set up a "WindowButtonMotionFcn" callback for your figure:
This callback will be triggered any time the cursor moves. Set the callback as a function handle pointing to a function that gets the "CurrentPosition" of the axes and displays these coordinates in the textbox:
To stop tracking the cursor, set up a "WindowButtonDownFcn" callback for your figure:
This callback will be triggered any time the user left-clicks inside the figure window. Set the callback as a function handle pointing to a function that sets the "WindowButtonMotionFcn" property to an empty string. This will prevent the tracking/recording function from being called when the mouse moves.
Below is an example, putting all these ideas together. Again, a callback is triggered whenever the user moves their mouse in the figure, and the mouse coordinates are displayed in the textbox. The recording of these coordinates will permanently stop when the user left-clicks on the
mouse and thus triggers the "WindowButtonDown" callback.
% Create figure with axes and textbox
f = figure;
ax = axes(f,'Units','normalized','Position',[.1 .3 .8 .6]);
txt = annotation(f,'textbox','FontSize',12,...
'Units','normalized','Position',[.1 .1 .35 .06],...
'BackgroundColor','white');
% set up callbacks for figure
f.WindowButtonMotionFcn = {@mouseMove,ax,txt};
f.WindowButtonDownFcn = @stopTracking;
% define callback functions
function mouseMove(~,~,ax,txt)
% get x and y position of cursor
xPos = ax.CurrentPoint(1,1);
yPos = ax.CurrentPoint(1,2);
% display coordinates in textbox
txt.String = "x: "+xPos+" y: "+yPos;
end
function stopTracking(f,~)
% stop callback to mouseMove
f.WindowButtonMotionFcn = "";
end
If you are unfamiliar with callbacks, here is a basic introduction to using callback functions in MATLAB:
And here are some other callbacks for figure windows: