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

后端 未结 1 1956
野性不改
野性不改 2021-01-16 04:29

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 missin

1条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-16 05:12

    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.

    0 讨论(0)
提交回复
热议问题