Created
March 12, 2024 13:41
-
-
Save raacampbell/a6f0574ec0af42a2b51b4f451e979a5e to your computer and use it in GitHub Desktop.
Rectangle whose free corner follows the mouse cursor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function mouse_rectangle | |
% Make a rectangle that is anchored at one corner at the axis origin but follows | |
% the mouse cursor at the other. | |
% | |
% Instructions | |
% Run "mouse_rectangle" then move mouse cursor over the axes. | |
% | |
% Inputs | |
% none | |
% | |
% Outputs | |
% None | |
% Build a pretty figure window | |
hFig = figure(123324); | |
clf(hFig) | |
hAx = axes(hFig); | |
set(hAx, ... | |
'XLim', [-1,1], ... | |
'YLim', [-1,1], ... | |
'XTick', [-1:1], ... | |
'YTick', [-1:1], ... | |
'Box', 'On') | |
% Set callback for mouse motion | |
set(hFig, ... | |
'MenuBar','none', ... | |
'WindowButtonMotionFcn', @mouseMoved_Callback) | |
% Indicate the axis origin with two intersecting lines | |
hold on | |
plot([-1,1],[0,0],'--k') | |
plot([0,0],[-1,1],'--k') | |
% Plot an invisible patch object that will follow the mouse cursor | |
hPatch = patch([0,0,0,0], [0,0,0,0],1); | |
set(hPatch, ... | |
'EdgeColor', 'r', ... | |
'FaceColor', [1,0.9,0.9]); | |
%% Internal functions follow | |
function mouseMoved_Callback(src,~) | |
% This callback runs every time the mouse moves over the figure window | |
ax = src.Children; % There is just one child, so don't index or check what it is | |
mousePos = ax.CurrentPoint(1,1:2); | |
% Bail out if the mouse is out of range | |
if any(abs(mousePos)>1) | |
return | |
end | |
% Get the properties of the rectangle and modify them | |
mouseX = mousePos(1); | |
mouseY = mousePos(2); | |
hPatch = findobj(ax.Children,'Type','Patch'); | |
hPatch.XData(2:3) = mouseX; | |
hPatch.YData(3:4) = mouseY; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment