How to enable responsive design for Fabric.js

Can I resize the Fabric.js canvas using a browser so that the same result is obtained on any device? I am talking about flexible design.

Does anyone have some sample code?

+4
source share
2 answers

Basically you need to get the width and height of the device screen. Subsequently, 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 may have screens with different resolution coefficients, although in this case I usually do a calculation of my original width and the width coefficient of the device, and then change both the width and the height accordingly. 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;

, , .

+5

, - , , .

. , , .

function rescale_canvas_if_needed()
{
	var optimal_dimensions = get_optimal_canvas_dimensions();
	var scaleFactor=optimal_dimensions[0]/wpd.canvas_w;
	if(scaleFactor != 1) {
		wpd_editor.canvas.setWidth(optimal_dimensions[0]);
		wpd_editor.canvas.setHeight(optimal_dimensions[1]);
		wpd_editor.canvas.setZoom(scaleFactor);
		wpd_editor.canvas.calcOffset();
		wpd_editor.canvas.renderAll();
  }
}

$( window ).resize(function() {
	clearTimeout(resizeId);
	resizeId = setTimeout(handle_resize, 500);
 });
 
 function handle_resize()
 {
	$(".canvas-container").hide();
	rescale_canvas_if_needed();
	$(".canvas-container").show();               
	 
 }
+4

Source: https://habr.com/ru/post/1528069/


All Articles