vega

How can I calculate the canvas size of a fully rendered Vega View?


The Vega View api includes functions to set/get the height and width, but they only indicate the properties of the charted area. They leave out the axes, key, labels and padding. I want to know the full height and width when all of these are factored in. I included the padding and origin (X,Y), but that still doesn't add up to the true size of the rendered canvas.

For example, I have tried

const view = new View(parse(compiledSpec))
   .render('canvas')
   .initialize(*/my DOM element*/);
view.runAsync().then(() => {
   const size = {
      width: view.width(),
      height: view.height(),
      padding: view.padding() as { top: number, right: number, bottom: number, left: number },
      origin: { x: view.origin()[0], y: view.origin()[1] }
   };
   updateCanvasSize({
      width: size.width + size.padding.left + size.padding.right + size.origin.x, 
      height: size.height + size.padding.top + size.padding.bottom + size.origin.y
   });
})

That still does not calculate the full height and width in all cases. My workaround is to check the size of the element through the DOM after rendering, but there must be a way to get the right numbers from the Vega api, right?


Solution

  • To calculate the full canvas size of a fully rendered Vega View, including axes, labels, and padding, you can use the view.container() method to get the DOM element containing the rendered view. This method will give you the actual dimensions of the rendered visualization, including all elements.

    I have updated your code that uses view.container() to get the full size:

    const view = new View(parse(compiledSpec))
       .render('canvas')
       .initialize(/* my DOM element */);
    
    view.runAsync().then(() => {
       const container = view.container();
       const size = {
          width: container.clientWidth,
          height: container.clientHeight
       };
       updateCanvasSize(size);
    });
    

    This should give you the accurate size you need without additional calculations. Let me know if this helps