Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

renderAll() not working in fabric.js

I have six floors of a building drawn on a canvas with fabric.js. In order to show only one floor, I do this:

building.selectFloor = function(floorId){

    for (var i = 0; i < floors.length; i++){
        if (floorId == floors[i].name){
            floors[i].visible = true;
        }else{
            floors[i].visible = false;          
        }
    }
    canvas.renderAll();
};

But nothing changes - all floors are still visible. The floors set to visible = false don't disappear until renderAll() is called later on a window resize:

$(window).resize(setSize);
setSize();


function setSize(){
    viewportWidth = $(window).width();
    viewportHeight = $(window).height();
    $appContainer.css({ "width": viewportWidth, "height": viewportHeight}); 
    canvas.setDimensions({ width: viewportWidth, height: viewportHeight });
    if (canvas.building){
        canvas.building.center();
        canvas.building.scaleX = canvas.building.scaleY = (viewportWidth + viewportHeight) / (1920 + 1080);
        canvas.renderAll();
    }
}

but then they do disappear. Why is one renderAll() working, and the other not? I've tried wrapping the non-functioning renderAll() in a window.timeOut to see if a delay helps, but no luck.

like image 426
wagster Avatar asked Nov 02 '25 01:11

wagster


2 Answers

Ok - so I figured it out in the end: building is a group which appears to be getting cached by some internal fabric magic, and the cached version is being rendered instead of the updated version. To render the updated version you have to do this

canvas.building.set('dirty', true);
canvas.renderAll();

Hope that helps someone on down the line.

EDIT

Turns out there's an easier solution still:

canvas.building.objectCaching = false
like image 131
wagster Avatar answered Nov 04 '25 14:11

wagster


There is a new version that changed the format to:

canvas.requestRenderAll();
like image 42
Ivan Ferrer Avatar answered Nov 04 '25 15:11

Ivan Ferrer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!