修改后获取画布对象尺寸

时间:2016-12-29 09:24:33

标签: jquery fabricjs

使用以下代码将Rect对象添加到画布中:

canvas = new fabric.Canvas("mycanvas");

// create a rectangle object
var rect = new fabric.Rect({
    left: 30,
    top: 30,
    fill: "green",
    width: 80,
    height: 40
});

// "add" rectangle onto canvas
canvas.add(rect);

我选择了Rect并调整它的大小。我的要求是:在调整大小后获得新的宽度和高度。

我曾尝试使用object:modified事件但没有成功。以下是对象的代码段:修改过的事件:

canvas.on("object:modified", function (options) {
    var width = options.target.width;
    var height = options.target.height;

    $("#widthTextBox").val(width);
    $("#heightTextBox").val(height);
});

提前谢谢。

1 个答案:

答案 0 :(得分:0)

不要使用宽度或高度,而是使用getWidth和getHeight

像这样:https://jsfiddle.net/ntLcfv2b/

canvas = new fabric.Canvas("my-canvas");

// create a rectangle object
var rect = new fabric.Rect({
    left: 30,
    top: 30,
    fill: "green",
    width: 80,
    height: 40
});

// "add" rectangle onto canvas
canvas.add(rect);


canvas.on("object:modified", function (e) {
    var activeObject = e.target;
    if (!activeObject) {
      return;
    }
    var width = activeObject.getWidth();
    var height = activeObject.getHeight();

    $("#widthTextBox").val(width);
    $("#heightTextBox").val(height);
});

所有FabricJS活动

General

after:render — fired continuously after each frame is rendered
before:render — fired before each frame is rendered
canvas:cleared — fired after a call to canvas.clear()
Mouse related

mouse:over
mouse:out
mouse:down — fired when mousedown event occurred on canvas
mouse:up — fired when mouseup event occurred on canvas
mouse:move — fired when the mouse is moving over the canvas
mouse:wheel - fired when using the scroll wheel
Object related

object:added — fired after object has been added
object:modified — fired after object is modified (moved, scaled, rotated)
object:moving — fired continuously during object movement
object:over — fired when mouse is over object (see example below)
object:out — fired when mouse is moved away from object (see example below)
object:removed — fired when object has been removed
object:rotating — fired continuously during object rotating
object:scaling — fired continuously during object scaling
object:selected — fired when object is selected
Path related

path:created — fired when (free-drawn) path is created
Selection related

before:selection:cleared — fired before selection is cleared (before active group is destroyed)
selection:cleared — fired after selection is cleared (after active group is destroyed)
selection:created — fired after selection is created (after active group is created)
Text related

text:editing:entered
text:editing:exited
text:selection:changed
text:changed