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

11 ビュー (過去 30 日間)
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?

採用された回答

MathWorks Support Team
MathWorks Support Team 2025 年 11 月 10 日
編集済み: MathWorks Support Team 2025 年 11 月 10 日
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:

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeGraphics Object Programming についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by