在Fabric js中加载画布后如何更改其宽度

时间:2018-07-15 14:32:49

标签: javascript html fabricjs

我想在画布加载后更改其宽度和高度。可以这样做。我想单击按钮或在页面加载中进行更改。我有两个动态变量的宽度和高度。

(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>

2 个答案:

答案 0 :(得分:0)

当然可以。

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

然后记住也要调用它以确保它被压扁!

canvas.calcOffset();

答案 1 :(得分:0)

使用canvas.setDimensions设置画布的宽度/高度。

演示

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>