Mouse position drawing varies on window resizing

this is one I’ve been trying to figure out for a few days, and really am coming up dry now.

but when i have this scaleable drawing running, the mouse position is always off. especially when i scale up the window. it just is never on point.
its fine if i take the scaling off, but i want it on, so everything is always in frame, no matter how big or small it gets.

does anyone know how this can be fixed? or a work around?
i have some code below to look at.

here is the drawing code. but more importantly, the scaling portion. which is reading the width and height

//from .cpp
void DrawClass::setup(){
    fbo.allocate(ofGetWindowWidth(), ofGetWindowHeight());

void DrawClass::draw(){
    ofRectangle drawWindow;
    drawWindow.setFromCenter(ofGetWindowWidth()/2, ofGetWindowHeight()/2, ofGetWindowWidth(), ofGetWindowHeight()-30);
    ofRectangle drawRect(0, 0, videoClass.videoPlayer.getWidth(), videoClass.videoPlayer.getHeight());
    ofRectangle drawFullscreenRect = drawRect;

void DrawClass::mouseDragged(int x, int y, int button){
    fbo.begin(); // draw on fbo instead of screen
    ofSetColor(brushRed, brushGreen, brushBlue, brushAlpha);
    ofCircle(x, y, brushWidth);

Assuming the fbo size is width x height, and that you draw it with fbo.draw(viewRect), this code can help you to convert the mouse screen coords (x,y) to the fbo coords:

void DrawClass::brush(float x, float y)
    x = x - viewRect.x;
    y = y - viewRect.y;
    Now (x,y)=(0,0) if the mouse is at the upper left corner of viewRect

    x = x / viewRect.width;
    y = y / viewRect.height;
    Now x and y are between 0 and 1 (if the mouse is in the viewRect)
    x=0 if the mouse is at the left of the viewRect
    x=1 if the mouse is at the right of the viewRect
    x=0.5 if the mouse is at the middle of the viewRect
    Same thing for y, but verticaly

    x = x * width;
    y = y * height;
    Now x is between 0 and width, and y is between 0 and height (if the mouse is in the viewRect)
    We can use them to draw at the correct location.

    // Short form:
    // x = ( x - viewRect.x ) / viewRect.width * width;
    // y = ( y - viewRect.y ) / viewRect.height * height;

    ofSetColor(200, 0, 0, 150);
    ofCircle(x, y, 15);

The .zip contains a working (2.5 KB)

1 Like

oh wow. ill give that a look see and give my results.

many many thanks :wink:

And btw, you can either do the same thing with ofMap():

x = ofMap( x, viewRect.getLeft(), viewRect.getRight(), 0, width );
y = ofMap( y, viewRect.getTop(), viewRect.getBottom(), 0, height );

(I always forget this helper function)