responsive-designhtml5-canvasfabricjs

How to enable responsive design for Fabric.js


Is there a way to make a Fabric.js canvas resize with the browser to enable the same result on any device? I'm talking about responsive design.

Has anyone a code example?


Solution

  • Basically you need to get the device screen's width and height. Afterwards just resize the canvas accordingly in your Javascript. Example:

    var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
    var height = (window.innerHeight > 0) ? window.innerHeight : screen.height;
    var canvas = document.getElementById("canvas");
    canvas.width = width;
    canvas.height = height;
    

    You might have screens with varying resolution ratios though, what I usually do in this case is calculate your original width's and the device's width ratio and then adjust both width and height accordingly with that value. Example:

    var originalWidth = 960;  //Example value
    var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
    var widthRatio = originalWidth / width;
    canvas.width *= widthRatio;
    canvas.height *= widthRatio;
    

    This usually works fine for me on any device, hope this helps.