Line 的 fabricjs loadFromJSON 子类

fabricjs loadFromJSON subclass of Line

我正在使用 答案并且对我来说工作正常。 当我使用 canvas 创建 json 并尝试使用 loadFromJSON 方法将其设置在另一个 canvas 上时,问题就来了。 我认为问题是这个新的子类没有 fromObject 方法,我尝试输入它,但我写不出任何有用的东西。

这就是我定义子类的方式(它几乎是从 link 复制粘贴)

fabric.LineaBote = fabric.util.createClass(fabric.Line, {
type: 'linea_bote',

initialize: function (element, options) {
    options || (options = {});
    this.callSuper('initialize', element, options);

    // Set default options
    this.set({
        hasBorders: false,
        hasControls: false,
    });
},

_render: function (ctx) {
    this.callSuper('_render', ctx);
    ctx.save();
    const xDiff = this.x2 - this.x1;
    const yDiff = this.y2 - this.y1;
    const angle = Math.atan2(yDiff, xDiff);
    ctx.translate(xDiff / 2, yDiff / 2);
    ctx.rotate(angle);
    ctx.beginPath();
    ctx.closePath();
    ctx.fillStyle = this.stroke;
    ctx.fill();
    ctx.restore();
    var p = this.calcLinePoints();
    var point = this.pointOnLine(this.point(p.x2, p.y2), this.point(p.x1, p.y1), 15)
    this.wavy(this.point(p.x1, p.y1), point, this.point(p.x2, p.y2), ctx);
    ctx.stroke();
},

point: function (x, y) {
    return {
        x: x,
        y: y
    };
},

wavy: function (from, to, endPoint, ctx) {
    var cx = 0,
        cy = 0,
        fx = from.x,
        fy = from.y,
        tx = to.x,
        ty = to.y,
        i = 0,
        step = 2,
        waveOffsetLength = 0,

        ang = Math.atan2(ty - fy, tx - fx),
        distance = Math.sqrt((fx - tx) * (fx - tx) + (fy - ty) * (fy - ty)),
        amplitude = -3,
        f = Math.PI * distance / 10;

    for (i; i <= distance; i += step) {
        waveOffsetLength = Math.sin((i / distance) * f) * amplitude;
        cx = from.x + Math.cos(ang) * i + Math.cos(ang - Math.PI / 2) * waveOffsetLength;
        cy = from.y + Math.sin(ang) * i + Math.sin(ang - Math.PI / 2) * waveOffsetLength;
        i > 0 ? ctx.lineTo(cx, cy) : ctx.moveTo(cx, cy);
    }
    ctx.lineTo(to.x, to.y);
    ctx.lineTo(endPoint.x, endPoint.y);
},

pointOnLine: function (point1, point2, dist) {
    var len = Math.sqrt(((point2.x - point1.x) * (point2.x - point1.x)) + ((point2.y - point1.y) * (point2.y - point1.y)));
    var t = (dist) / len;
    var x3 = ((1 - t) * point1.x) + (t * point2.x),
        y3 = ((1 - t) * point1.y) + (t * point2.y);
    return new fabric.Point(x3, y3);
},

toObject: function () {
    return fabric.util.object.extend(this.callSuper('toObject'), {
        customProps: this.customProps,
    });
},});

下面是我尝试编写 fromObject() 函数的方式:

fabric.LineaBote.fromObject = function (points, callback) {
callback && callback(new fabric.LineaBote(points, object));};

来自 google chorme 控制台的错误:未捕获的类型错误:无法读取未定义的 属性 'fromObject'

正如我所想,问题是未定义 fromObject。作者更新了原来的post写了函数。感谢他。