fabric.js:始终可见的控件

fabric.js: Always visible controls

我正在使用 fabric.js 进行图像处理,效果很好,但我需要控件始终可见,即使我在 object/image 之外单击也是如此。

默认情况下,它们仅在您单击 objec/image 时可见,如果您在其外部单击,控件就会消失。

可以吗?

谢谢。

遗憾的是,目前 FabricJS 中没有内置方法来实现这一点。

但是,这里有一个解决方法 (function) ,它将模拟此功能 ​​...

function showControls(...objs) {
   objs.forEach(obj => {
      obj.set('active', true);
      canvas.renderAll();
      canvas.on('mouse:down', function(e) {
         obj.set('active', true);
      });
   })
}

在 canvas 上添加图像对象后,调用上述函数并将图像对象作为参数传递,您希望为其显示控件。

ᴅᴇᴍᴏ

var canvas = new fabric.Canvas('c');
// add rectangle (for demo purposes only)
var rect = new fabric.Rect({
   top: 100,
   left: 290,
   width: 100,
   height: 100,
   fill: '#07C',
   originX: 'center',
   originY: 'center',
   transparentCorners: false
});
canvas.add(rect);
// add image (for demo purposes only)
fabric.Image.fromURL('https://i.imgur.com/Q6aZlme.jpg', function(img) {
   img.set({
      top: 100,
      left: 110,
      width: 100,
      height: 100,
      originX: 'center',
      originY: 'center',
      transparentCorners: false
   })
   canvas.add(img);
   showControls(img); // pass an object that you wish to show controls for
});

// always show controls (multi-object support)
function showControls(...objs) {
   objs.forEach(obj => {
      obj.set('active', true);
      canvas.renderAll();
      canvas.on('mouse:down', function(e) {
         obj.set('active', true);
      });
   })
}
canvas{border:1px solid #ccc}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.11/fabric.min.js"></script>
<canvas id="c" width="400" height="200"></canvas>

不完美,但一个开始


// fabricjs object - always show controls

//fabric.Object.prototype.render = (function (render) {
fabric.Image.prototype.render = (function (render) {
    return function (ctx) {
        render.apply(this, arguments)

        // show controls
        // but most controls are not usable
        // until you activate [click] the object
        this._renderControls(ctx)

        // activate this object
        // to make all controls usable
        // only one active object per canvas
        // when another object is active
        // the controls become not usable
        if (!this.canvas._activeObject)
            this.canvas._activeObject = this
    }
//})(fabric.Object.prototype.render)
})(fabric.Image.prototype.render)



// fabricjs object - activate on mouseover
// this is just a quick hack
// to make controls always usable

//fabric.Object.prototype.initialize = (function (initialize) {
fabric.Image.prototype.initialize = (function (initialize) {
    return function () {
        initialize.apply(this, arguments)

        this.on('mouseover',
        function(event) {
            this.canvas.setActiveObject(this)
            this.canvas.renderAll() // TODO cheaper?
        })
    }
//})(fabric.Object.prototype.initialize)
})(fabric.Image.prototype.initialize)