所以我找到了这个解决方案。不完美,但它有效。
虽然 Fabric 根据 width 和 height 参数调整对象的绘画区域大小,但我必须自己设置宽度和高度参数。
Fabric 的宽度和高度设置为绘画区域的大小,而我的宽度和高度设置为矩形的实际大小(没有“耳朵”的矩形)。
开始,先定义类:
var CustomRect = fabric.util.createClass(fabric.Object, {
initialize: function(options) {
options || (options = { });
if (options.width || options.height){
alert('Do not use width/height, use my_width/my_height instead.');
}
// here we set our Object's width, height to create painting area for it
// It must be little larger than rectangle itself to paint "ears"
options.width = options.my_width + SIZE_EXTEND;
options.height = options.my_height + SIZE_EXTEND;
this.callSuper('initialize', options);
},
_render: function(ctx) {
var PIx2 = 6.28319; // 2 * PI
var w_half = (this.width - SIZE_EXTEND) / 2;
var h_half = (this.height - SIZE_EXTEND) / 2;
ctx.rect(this.left, this.top, this.width - SIZE_EXTEND, this.height - SIZE_EXTEND);
ctx.fill();
// "ears"
ctx.beginPath();
ctx.arc(-w_half, -h_half, 4, 0, PIx2, false);
ctx.fill();
ctx.beginPath();
ctx.arc(w_half, -h_half, 4, 0, PIx2, false);
ctx.fill();
ctx.beginPath();
ctx.arc(-w_half, h_half, 4, 0, PIx2, false);
ctx.fill();
ctx.beginPath();
ctx.arc(w_half, h_half, 4, 0, PIx2, false);
ctx.fill();
}
}
SIZE_EXTEND 是在别处定义的常量(因为我的应用程序常量是可以的)。
现在我如何在我的应用程序中使用它。在我的画布上添加一个新矩形:
var TheCanvas;
TheCanvas = new fabric.Canvas('mainCanvas');
TheCanvas.setWidth(window.innerWidth);
TheCanvas.setHeight(window.innerHeight);
TheCanvas.add(new CustomRect({
left: 500,
top: 200,
my_width: 100, // here I define size WITHOUT "ears"
my_height: 100
}));