问题
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