【问题标题】:fabricjs: _render method of my fabric.Object subclass is never calledfabricjs:我的 fabric.Object 子类的 _render 方法永远不会被调用
【发布时间】:2016-12-15 16:57:25
【问题描述】:

initialize 方法被调用,但 render 方法没有被调用。 我在the fabricjs website 上阅读了有关子类化的信息,并查看了demo。 我真的不明白我的代码中缺少什么。

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

type: "customCircle",

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

_render: function (ctx) {
    ctx.beginPath();
    ctx.arc(100, 250, 50, 0, 2 * Math.PI, false);
    ctx.fillStyle = 'green';
    ctx.fill();
    ctx.lineWidth = 5;
    ctx.strokeStyle = '#003300';
    ctx.stroke();

}
});

  var customCircle = new CustomCircle();
  canvas.add(customCircle);

Here is a fiddle.

【问题讨论】:

  • 如果我写 render 而不是 _render 似乎可以工作 - 我不明白为什么......
  • 好的,我不确定这是修复还是技巧,但是如果我在创建 customCircle 时提到 with& height ,则调用 _render: new CustomCircle({width:1, height:1} );但是在代码中宽度为 1 和高度为 1 是无意义的,而 cercle 比这大得多......任何关于我所说的内容的 cmets 或答案都会很有用。谢谢!
  • 嗨。你能解决这个问题吗?我现在遇到了同样的问题:/
  • 我发布了解决方案

标签: render fabricjs


【解决方案1】:

当您想要创建自定义对象时,您可以自行计算和设置最新对象的宽度和高度。为此,您可以在 initialize 函数中调用 this.set({width: ..., height: ...})

var canvas = new fabric.Canvas('c');

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

    radius: 50, 

    type: "customCircle",

    initialize: function (options) {
        this.callSuper('initialize', options);
       this.set({ width: 2 * this.radius, height: 2 * this.radius });
   },

    _render: function (ctx) {
        ctx.beginPath();
        ctx.arc(0, 0, this.radius, 0, 2 * Math.PI, false);
        ctx.fillStyle = 'green';
        ctx.fill();
        ctx.lineWidth = 5;
        ctx.strokeStyle = '#003300';
       ctx.stroke();

     }
 });

var customCircle = new CustomCircle({left:50, top:50});

canvas.add(customCircle);

See the fiddle

还要注意,在 _render 函数中,画布已经被翻译到您的自定义对象的中心。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多