Viraj Madushanka
Viraj Madushanka

Reputation: 71

How can we change canvas width height after it loads in Fabric js

I want to change the width and height of the canvas after it's load.Is that possible to do.I want to do it with a button click or in page load. I have two dynamic variables for Width and height.

(function() {
    var canvas = this.__canvas = new fabric.Canvas('canvas');
  
    // create a rectangle with a fill and a different color stroke
    var rect = new fabric.Rect({
       left: 50,
       top: 50,
       width: 50,
       height: 50,
       fill: 'rgba(255,127,39,1)',
       stroke: 'rgba(34,177,76,1)',
       strokeWidth: 5
    });
    canvas.add(rect);
    canvas.renderAll();    
})();

function(){
  var c_width = 500px;
  var c_height= 600px;

}
<canvas id="canvas" width="300" height="300"></canvas>
<button onclick="function()">change canvas </button>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>

<script src='https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.6/fabric.min.js'></script>

Upvotes: 3

Views: 2152

Answers (3)

Mohamed Raza
Mohamed Raza

Reputation: 973

var canvas define the fabric object and identifying the canvas element

oImg has the detail information of the Image

setDimensions method assist to set dynamic size of height and width for the selected canvas

            var canvas = new fabric.Canvas('inventory_line_sheet_attachment_canvas');
            fabric.Image.fromURL("http://fabricjs.com/article_assets/9.png", function(oImg) {
                canvas.setDimensions({
                    width:oImg.width,
                    height:oImg.height
                });
                canvas.add(oImg);
            });

Upvotes: 0

Durga
Durga

Reputation: 15614

Use canvas.setDimensions to set width/height of canvas.

DEMO

var canvas = this.__canvas = new fabric.Canvas('canvas');

// create a rectangle with a fill and a different color stroke
var rect = new fabric.Rect({
   left: 50,
   top: 50,
   width: 50,
   height: 50,
   fill: 'rgba(255,127,39,1)',
   stroke: 'rgba(34,177,76,1)',
   strokeWidth: 5
});
canvas.add(rect);
canvas.renderAll();

function resizeCanvas(){
  canvas.setDimensions({
   width:500,
   height:600
  });
}
canvas{
  border:2px solid #000;
}
<canvas id="canvas" width="300" height="300"></canvas>
<button onclick="resizeCanvas()">change canvas </button>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>

<script src='https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.6/fabric.min.js'></script>

Upvotes: 2

Fool
Fool

Reputation: 119

Sure you can.

canvas.setWidth(); canvas.setHeight();

Then remember to also call this to avid it getting squished!

canvas.calcOffset();

Upvotes: 0

Related Questions