konvajs / konva

Konva.js is an HTML5 Canvas JavaScript framework that extends the 2d context by enabling canvas interactivity for desktop and mobile applications.
http://konvajs.org/
Other
11.71k stars 933 forks source link

Resizing stage to parents <div> size #321

Closed uahic closed 6 years ago

uahic commented 6 years ago

This might not be really a konva issue but maybe you guys a good solution; As I am building an editor with konva, I would like to to have side-navs and the konva-stage consuming the remaining space on the display. I'd like to do this such that it is reactive to display-orientation/size changes (for the detection of this I employ stuff out of Angular 5's toolchain like flex-box).

Now there is an issue... I dont know how to access information how much space is remaining to maximize the width/height of the canvas (or better the parent element). There is an example in konva how to do it dynamically with the window size, but in my scenario the konva-stage has to share the space with other elements and - if possible - this should happen as much out-of-the-box as possible (means no manual computations that include accessing the side-navs directly as flex-box might positioning them below the canvas if the device-orientation changes 'portrait' to 'landscape')

are there any tricks I could do here?

thank you very much

seethroughdev commented 6 years ago

I see this is pretty old, but in case it still helps anyone. this should apply to most js frameworks:

You'll want to size your stage relative to a parent container. Using flexbox is great, because your container can fill height, and if you don't have that. your height will never be more than 0.

Angular, React etc… own the dom. so none of your nodes will initially load with accurate dimensions. Instead, you’ll want to listen for resize of the parent dom node, and onResize, update the attrs of your stage.

onMount: () => {
   stage = new Konva.Stage({...})
}

onResize: (contentRect) => {
  const { width, height } = contentRect
  stage.attrs({
     width,
     height
   })
   stage.batchDraw()
}

if you're going to add the listener by hand, check out ResizeObserver (polyfills available), that will give you a nice API for resizing, otherwise, i'd consider a plugin that uses it.

lavrton commented 6 years ago

I think that is a good answer. Thank you @seethroughtrees. I will close the issue.