fabricjs: _render method of my fabric.Object subclass is never called

半世苍凉 提交于 2019-12-19 11:20:08

问题


The initialize method is called but render method is not. I read about subclassing on the fabricjs website and looked at that demo. I really don't understand what is missing in my code.

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.


回答1:


When you want to create a custom object it is up to you to calculate and set the width and height of this latest. To do so you can call this.set({width: ..., height: ...}) inside the initialize function.

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

Also note that inside the _render function, the canvas has already been translated to the center of your custom object.



来源:https://stackoverflow.com/questions/26565436/fabricjs-render-method-of-my-fabric-object-subclass-is-never-called

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!