Search code examples
famo.us

Famo.us fit parent size


Not providing any size for a surface will make the surface taking the size of it's parent, for an image we call this a "fill".

enter image description here

But this distord the image, now how to make a surface (or whatever element with a size) to fit it's parent height or width keeping the elements ratio ?

Minimal code example:

var Engine = require('famous/core/Engine');
    var Surface = require('famous/core/Surface');

    var mainContext = Engine.createContext();
    var firstSurface = new Surface({
        size: [200, 100],
        content: 'How to make this surface fit its parent (mainContext) keeping the 2/1 size ratio ?',
        properties: {
            backgroundColor: 'orange'
        }
    });

    mainContext.add(firstSurface);

Solution

  • You can use the sizeFrom method on Modifier. The 'from' functions of Modifier are very useful in that you do not need to worry about binding to the engine resize event. Here is an example of what you are trying to achieve..

    Hope this helps!

    var Engine   = require('famous/core/Engine');
    var Surface  = require('famous/core/Surface');
    var Modifier = require('famous/core/Modifier');
    
    var mainContext = Engine.createContext();
    var firstSurface = new Surface({
        size: [undefined, undefined],
        content: 'How to make this surface fit its parent (mainContext) keeping the 2/1 size ratio ?',
        properties: {
            backgroundColor: 'orange'
        }
    });
    
    firstSurface.mod = new Modifier({ origin: [0.5,0.5] });
    
    firstSurface.mod.sizeFrom(function(){
    
        ratio         = (2.0/1.0) ;
        contextSize   = mainContext.getSize() ;
        contextRatio  = contextSize[0] / contextSize[1] ;
    
        width = ratio > contextRatio ? contextSize[0] : contextSize[1] * ratio ;
        height = width / ratio ;
        return [width,height] ;
    });
    
    mainContext.add(firstSurface.mod).add(firstSurface);