fabricJS-自定义对象未绘制在画布上

fabricJS - Custom object is not drawn on canvas

本文关键字:绘制 自定义 对象 fabricJS-      更新时间:2023-09-26

我正在fabricJS中试用自定义对象。我从自己画的一条线开始。我知道这已经有了一个对象,但我想了解背后发生了什么,以及我可以在多大程度上改变事情。所以,我用一条简单的线作为开头,但由于任何原因,它都没有画在画布上。

看起来_render函数没有被调用,而initialize工作正常。你能告诉我我的代码出了什么问题吗?

JSFiddle

fabric.CustomLine = fabric.util.createClass(fabric.Object, {
    type: 'customline',
    pos : {
        x1 : 0,
        y1 : 0,
        x2 : 0,
        y2 : 0
    },
    initialize: function (options) {
        options = options || {};
        this.callSuper('initialize', options);
        this.pos.x1 = options.x1 || 0;
        this.pos.y1 = options.y1 || 0;
        this.pos.x2 = options.x2 || 0;
        this.pos.y2 = options.y2 || 0;
    },
    _render : function (ctx) {
        ctx.beginPath();
        ctx.moveTo(this.pos.x1, this.pos.y1);
        ctx.lineTo(this.pos.x2, this.pos.y2);
        ctx.closePath();
        this._renderFill(ctx);
        this._renderStroke(ctx);
    }
});

编辑:

在这个问题上也有同样的问题。似乎必须将widthheight属性设置为> 0,但我不明白为什么。我在fabricJS源代码中也找不到这种解决方法。

因此_render函数由Object.render函数调用。

Object.render的启动方式如下:

    render: function(ctx, noTransform) {
      // do not render if width/height are zeros or object is not visible
      if ((this.width === 0 && this.height === 0) || !this.visible) {
        return;
      }
     ...
    }

对象在initialize函数中没有初始化任何宽度和高度,因此render方法立即返回,并且不会调用_render函数。