track the position of the mouse cursor

조회 수: 19 (최근 30일)
rukhsar khan
rukhsar khan 2017년 3월 18일
답변: Madheswaran 2025년 1월 9일
I want to track the position of the mouse cursor, for every seconds. Means when a mouse is moved - this tracker should start and plot the graph with respect to time( i.e; the x and y coordinate with respect to time). So how can i write this program in MATLAB.

답변 (1개)

Madheswaran
Madheswaran 2025년 1월 9일
Hi Rukhsar
You can use 'get(groot, "PointerLocation") to get the current location of the cursor. Consider the following code for creating a live plot of cursor movements:
fig = figure('Name', 'Mouse Position Tracker');
x_positions = [];
y_positions = [];
timestamps = [];
start_time = tic; % Start timer
subplot(2,1,1);
h1 = plot(0,0,'b-'); % X-coordinate plot
title('X-Coordinate vs Time');
xlabel('Time (seconds)');
ylabel('X Position (pixels)');
grid on;
subplot(2,1,2);
h2 = plot(0,0,'r-'); % Y-coordinate plot
title('Y-Coordinate vs Time');
xlabel('Time (seconds)');
ylabel('Y Position (pixels)');
grid on;
while ishandle(fig) % Run until figure is closed
% Get current mouse position
currentPos = get(groot, 'PointerLocation');
current_time = toc(start_time);
x_positions = [x_positions currentPos(1)];
y_positions = [y_positions currentPos(2)];
timestamps = [timestamps current_time];
set(h1, 'XData', timestamps, 'YData', x_positions);
set(h2, 'XData', timestamps, 'YData', y_positions);
% Adjust axes limits automatically
subplot(2,1,1);
xlim([max(0, current_time-10) current_time+0.1]);
subplot(2,1,2);
xlim([max(0, current_time-10) current_time+0.1]);
% Pause for 1 second before next update
pause(1);
end
This code creates a window with two graphs that show your cursor's X and Y positions over time. The top graph (blue line) tracks horizontal movement, and the bottom graph (red line) tracks vertical movement. It updates every second and shows the last 10 seconds of movement. The tracking continues until you close the window.
Here is the output of the above code:
For more information, refer to the following documentations:
  1. groot - https://mathworks.com/help/matlab/ref/groot.html
  2. get - https://mathworks.com/help/matlab/ref/get.html
Hope this helps!

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by