How to enable responsive design for Fabric.js

gco picture gco · Feb 21, 2014 · Viewed 13.5k times · Source

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?

Answer

Joao picture Joao · Feb 21, 2014

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.