when Fabric.js canvas can not select any objects with Nextjs

modric·2024년 4월 27일

(I wrote this for fellow on earth who suffer like me)

Problem Situation(eng)

I'm using fabric.js with Next.js, but clicks on objects (rectangles, images, etc.) are not available. Even though the objects are added to the Fabric canvas and the Fabric canvas area is draggable, the objects themselves aren't clickable. It's frustrating because everything seems to be functioning, but the objects aren't clickable. I'm torn between switching to Konva instead of fabric.js or just implementing everything from scratch.

cause:

Wow. I found it. There was another upper canvas layer blocking the mouse events like a glass window. That problem was so frustrating that I couldn't concentrate, even while watching soccer or walking around, I kept thinking about it. From yesterday, I've been stuck on this error all day long. At 5am, I was so frustrated that I missed Modric's strange ball handling in the live match ... After watching the replay, it was really adorable. What a waste...

Solution

Turn off React's restrict mode.

reactStrictMode: false

문제상황(kr)

fabric.js를 쓰고 있는데 object(rect, image ...) 등 클릭이 안됨. 오브젝트가 캔버스에 잘 add되고 캔버스 영역 드래그 되는 거 보면 동작하는 데 오브젝트만 클릭이 안되니 답답하고 fabric.js 말고 konva로 넘억야하는지, 걍 순정으로 다 구현해야할지 오만가지 생각이 교차함

원인

와. upper canvas가 하나더 위에 있어가지고 걔가 유리창처럼
마우스 이벤트를 막고 있었다.
내가 이거 진짜 너무 답답해가지고 축구도 보는둥 마는둥, 눕기전에도 생각하고 걸어다니면서도 이 생각하고 버스에서도 이 생각하고..ㅋㅋㅋㅋ

어제부터 하루 내내 이 에러에 매달렸다.
새벽에 너무 답답해서 이거 매달리다가 모드리치가 공 이상하다고 줍는 거 라이브 놓쳤음 ㅜ 리플레이 화면으로 봄.. 너무 아까워.. 그런데 아 진짜 이거였다고?

삽질 Futile attempts

여러가지 삽질을 했는데
1.
걍 처음부터 코드 다시 짜기
2.
좌표 문제가 싶어서 계속 좌표 가져오기
new Fabric.canvas를 잘 만들고 이미지도, 도형도 잘 그려지는데 도저희 클릭이 가능하지 않았다.

canvas에서 drag를 구현하는 방법은 그 오브젝트의 영역 안에서 마우스의 이벤트가 일어나면 마우스의 좌표가 움직임에 따라 이전의 오브젝트를 지우고 마우스의 위치에 오브젝트를 다시 그리는 방법으로 구현할 수 있다.
fabric.js도 순정 canvas와 옆에 있을때 우연히 발견한 에러 동작을 통해 이런 식으로 동작할것이라 나중에 코드를 보는 판단해야함 아무튼
drag라고 할 수 있는 selectable 기능은 그 오브젝트의 좌표를 이용해여 마우스의 무브먼트가 있을때 그 좌표값에 따라서 계속 지웠다가 렌더링해주는 이른바 리렌더링이라고 이해하고 있다.

그래서 나는 좌표를 못잡나 싶어서 애꿎은 setCoords();만 계속 업데이트해주고 있었다. 알아서 잘 알아먹으라는 뜻으로

fabricRef.current?.add(image);
image.setCoords();
image.center();
fabricRef.current.forEachObject(function (object) {
  object.setCoords();
});
fabricRef.current.requestRenderAll();

Solution

Turn off React's restrict mode.

reactStrictMode: false

profile
안녕하세요 카페에서 코딩하면 안 일어나기 라는 일을 잘합니다

0개의 댓글