Reputation: 567
I need to draw customized rectangle - the one with 4 "ears" in each corner.
So I defined my own class based on fabric.Object
like this:
var CustomRect = fabric.util.createClass(fabric.Object, {
...
}
Important note: when creating objects based on my class CustomRect
I want to define width
and height
as a size of a rectangle without those "ears".
But I have a problem. I can not draw outside of an area defined by width x height.
Everything else gets clipped - it's drawn but not visible. So I'm not able to draw those "ears" while they go beyond the limits of an area width x height.
How to tell fabric to extend drawing area? How can I draw outside of width x height area?
Many thanks guys!
Upvotes: 0
Views: 857
Reputation: 567
So I have found this solution. Not perfect but it works.
While Fabric adjusts the size of painting area for an object according to it's width
and height
parameters, I had to make my own width and height parameters.
Fabric's width and height are set to the size of painting area, while my width and height are set to the real size of a rectangle (rectangle without "ears").
Here we go, class definition first:
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
is a constant defined elsewhere (for my application constant is OK).
And now how I use it in my application. Adding a new rectangle onto my canvas:
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
}));
Upvotes: 2