pikasojs / pikaso

Seamless, headless and fully tested HTML5 Canvas library
https://pikaso.app
MIT License
216 stars 17 forks source link

A suggestion to avoid canvas leak on iOS/Mac safari #81

Open bupthcp opened 1 year ago

bupthcp commented 1 year ago

When I was using Pikaso, I found a canvas leak problem on webbiew/safari of iOS and Safari of Mac and Windows. It's not a bug of Pikaso or Konva-JS, it may be an bad implementaion of iOS webview. But using pikaso in some way will cause the canvas leak ,and reach the limi of 384M memory of iOS,then no canvas can be operated on the web page. Let me describe the detail of the problem.

  1. Every konva stage and layer has two canvas. (https://konvajs.org/docs/how_it_works.html) Canvas of a stage can be accessed by stage.bufferCanvas._canvas and stage.bufferHitCanvas._canvas. Canvas of a Layer can be accessed by layer.canvas._canvas and layer.hitCanvas.
  2. When konvajs is running on iOS safari or MAC safari , any change of url will not cause the release of konva canvas. You can have a test on this, and the amount of canvas can be traced by safari inspector (the graphics module). So we need to release the canvas by setting the canvas width and height to 1.
  3. Pikaso has two processes that can cause konva stage clone, so we may also need to manually release canvas in these two process. (1) The loading process. The reset function will create a new konva stage, so the elder stage may need to be released manually

(2) The setImageFromUrl function. It will create a history state with a konva stage and a snapshot will be clone from the stage. The snapshot is a local variable, so the canvas of the snapshot will cause a leak.

raminious commented 1 year ago

Thanks @bupthcp

I found your explanation to be very detailed and interesting. I was not aware of such behavior in Safari. I tried playing with this and totally agree with your description. In the next month, I'll fix that.

https://user-images.githubusercontent.com/334716/216724158-d97f7489-06d3-4e9b-a774-dd1057c7f119.mp4