How do I continuously track / record coordinates of my cursor over an axes in my figure window?

11 visualizaciones (últimos 30 días)
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?

Respuesta aceptada

MathWorks Support Team
MathWorks Support Team el 10 de Nov. de 2025
Editada: MathWorks Support Team el 10 de Nov. de 2025
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:
https://www.mathworks.com/help/matlab/creating_plots/create-callbacks-for-graphics-objects.html
And here are some other callbacks for figure windows:

Más respuestas (0)

Categorías

Más información sobre Graphics Object Programming en Help Center y File Exchange.

Productos


Versión

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by