Hnus
Hnus

Reputation: 959

How to calculate mouse position relative to drawing area when it hovers over element being drawn

Imagine simple ms paint application written in react and you are trying to implement rectangle drawing.

It's something I currently have but if I drag my mouse over rectangle I am currently drawing it starts to flicker because it fires event with position relative to rectangle and not drawing area (in my case div) depending over which element (drawing area/rectangle) my mouse is currently over.

I have extracted the problem into this simple app https://codesandbox.io/s/6yxx4y9lz3

I feel like I could solve the problem with hacky calculations but I would appreciate some elegant solution/advice as this functionality is going to be base stone of bigger application.

Upvotes: 1

Views: 52

Answers (1)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195972

The actual problem is that the blue box you are drawing eats up the mouse events.

You can just add pointer-events:none to it so that it is ignored. (pointerEvents when used from inside React)

style={{
    width: item.w,
    height: item.h,
    top: item.y,
    left: item.x,
    border: "solid blue",
    position: "absolute",
    pointerEvents:"none"
}}

Updated demo at https://codesandbox.io/s/l7ll3wy5pl

Upvotes: 1

Related Questions