【问题标题】:Customized shape in Fabric - how to draw beyond it's size?Fabric 中的定制形状 - 如何绘制超出它的尺寸?
【发布时间】:2017-05-09 11:10:00
【问题描述】:

我需要绘制自定义矩形 - 每个角落有 4 个“耳朵”的矩形。

所以我根据fabric.Object 定义了自己的类,如下所示:

var CustomRect = fabric.util.createClass(fabric.Object, {
...
}

重要提示:基于我的类CustomRect 创建对象时,我想将widthheight 定义为没有那些“耳朵”的矩形的大小。

但是我有一个问题。 我无法在由 width x height 定义的区域之外进行绘制

其他所有内容都被剪裁了 - 已绘制但不可见。因此,当它们超出区域宽度 x 高度的限制时,我无法绘制那些“耳朵”。

如何告诉fabric扩展绘图区域?如何在 width x height 区域之外绘制?

非常感谢各位!

【问题讨论】:

  • 你试过用一个矩形和四个圆组成的组吗?
  • 请添加可执行的sn-p或自定义对象的代码
  • @Ben 好主意。但是我想通过设置宽度/高度来轻松修改对象的大小,并且在组中这并不容易。需要相应地移动圆圈...群组可以接收诸如“修改”之类的事件以以某种自动化方式调整圆圈吗?
  • 此时您所拥有的一个示例将非常方便。

标签: javascript html5-canvas fabricjs


【解决方案1】:

所以我找到了这个解决方案。不完美,但它有效。

虽然 Fabric 根据 widthheight 参数调整对象的绘画区域大小,但我必须自己设置宽度和高度参数。

Fabric 的宽度和高度设置为绘画区域的大小,而我的宽度和高度设置为矩形的实际大小(没有“耳朵”的矩形)。

开始,先定义类:

var CustomRect = fabric.util.createClass(fabric.Object, {

    initialize: function(options) {

        options || (options = { });

        if (options.width || options.height){
            alert('Do not use width/height, use my_width/my_height instead.');
        }

        // here we set our Object's width, height to create painting area for it
        // It must be little larger than rectangle itself to paint "ears"
        options.width = options.my_width + SIZE_EXTEND;
        options.height = options.my_height + SIZE_EXTEND;

        this.callSuper('initialize', options);
    },

    _render: function(ctx) {

        var PIx2 = 6.28319; // 2 * PI
        var w_half = (this.width - SIZE_EXTEND) / 2;
        var h_half = (this.height - SIZE_EXTEND) / 2;

        ctx.rect(this.left, this.top, this.width - SIZE_EXTEND, this.height - SIZE_EXTEND);
        ctx.fill();
        // "ears"
        ctx.beginPath();
        ctx.arc(-w_half, -h_half, 4, 0, PIx2, false);
        ctx.fill();
        ctx.beginPath();
        ctx.arc(w_half, -h_half, 4, 0, PIx2, false);
        ctx.fill();
        ctx.beginPath();
        ctx.arc(-w_half, h_half, 4, 0, PIx2, false);
        ctx.fill();
        ctx.beginPath();
        ctx.arc(w_half, h_half, 4, 0, PIx2, false);
        ctx.fill();
    }
}

SIZE_EXTEND 是在别处定义的常量(因为我的应用程序常量是可以的)。

现在我如何在我的应用程序中使用它。在我的画布上添加一个新矩形:

    var TheCanvas;

    TheCanvas = new fabric.Canvas('mainCanvas');
    TheCanvas.setWidth(window.innerWidth);
    TheCanvas.setHeight(window.innerHeight);

    TheCanvas.add(new CustomRect({
        left: 500,
        top: 200,
        my_width: 100, // here I define size WITHOUT "ears"
        my_height: 100
    }));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 2014-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-12
    相关资源
    最近更新 更多