I'm new to fabricjs (and to Javascript development in general). I am "porting" a legacy Flex/Actionscript project and need to enable the user to create a complex clipping path for an image.
My approach in Actionscript was to use the Actionscript Graphics class using BlendMode.ERASE to "erase" from the yellow base rectangle (i.e. give the appearance of erasing) and then using that set of rects to create a bitmap to serve as an alpha channel for the final image (Step 3) created on the fly.
Can anyone suggest how I might accomplish a similar functionality in Fabric? It doesn't seem to support HTML5 Canvas Blend modes and while I see that it supports clipping paths for images, I'm not seeing how I can enable the user to interactively create a clipping path without doing lots of intersection checks to try to derive the points to create a new path on the fly.
Thanks!
Step 1: After the user has drawn a base rectangle, drag-option/alt-key enables them to draw a rectangle (the red line) which will be subtracted from the base rect.
Step 2: The base rect is shown with the subtraction.
Step 3: The base rect is used to clip or mask a section of the base image
Step 1
Step 2
Step 3
Will Tower,
There is no easy way to do it. Here are the steps:
Draw 'Yellow' rectangle
Draw 'Red' rectangle
Use clipping library like PolyBool for intersection and xor operations
Convert drawing result into the clipped path of combining rectangles
clip your image
I created some quick fiddle. You have to click on a each button to clip. It won't clip if you will not add 2 rectangles on the canvas. This is very simple example. In order to work properly you have to draw rectangles with mouse (make them dynamic). Also, this logic is not accounting for these variations (you have to work on them as well):
For these use cases Clipping Library will return to you 2 set of results, which means different logic should be implemented.
Actual code without jQuery, FabriJs, and PolyBool libraries:
var imgURL = 'http://fabricjs.com/lib/pug.jpg';
var clipYellowRect = null;
var clipRedRect = null;
var pug = null;
var canvas = new fabric.Canvas('c');
// insert image into canvas
var pugImg = new Image();
pugImg.onload = function (img) {
pug = new fabric.Image(pugImg, {
angle: 0,
width: 500,
height: 500,
left: 100,
top: 50,
scaleX: 0.5,
scaleY: 0.5,
clipName: 'pug',
});
canvas.add(pug);
};
pugImg.src = imgURL;
//draw yellow rectangle
$('#btnYellowRect').on('click', function(){
clipYellowRect = new fabric.Rect({
originX: 'left',
originY: 'top',
left: 120,
top: 60,
width: 200,
height: 200,
fill: 'rgba(255,255,0,0.5)',
strokeWidth: 0,
selectable: false
});
canvas.add(clipYellowRect);
});
//draw red rectangle
$('#btnRedRect').on('click', function(){
clipRedRect = new fabric.Rect({
originX: 'left',
originY: 'top',
left: 90,
top: 120,
width: 100,
height: 100,
strokeWidth: 3,
fill: 'transparent',
stroke: 'rgba(255,0,0,1)', /* use transparent for no fill */
strokeWidth: 0,
selectable: false
});
canvas.add(clipRedRect);
});
//clip
$('#btnClip').on('click', function(){
var yellowRectRegion = getRegion(clipYellowRect);
var redRectRegion = getRegion(clipRedRect);
//determine inersection
var intersectResult = PolyBool.intersect({
regions: [yellowRectRegion],
inverted: false
}, {
regions: [redRectRegion],
inverted: false
});
//generate clipping path
var xorResult = PolyBool.xor({
regions: [yellowRectRegion],
inverted: false
}, {
regions: intersectResult.regions,
inverted: false
});
clipImage(xorResult.regions[0]);
});
//prepare data for clipping library
function getRegion(rect){
return [[rect.left, rect.top],
[rect.left + rect.width, rect.top],
[rect.left + rect.width, rect.top + rect.height],
[rect.left, rect.top + rect.height]]
}
function clipImage(points){
//actual clipping
pug.clipTo = function (ctx) {
var scaleXTo1 = (1 / pug.scaleX);
var scaleYTo1 = (1 / pug.scaleY);
ctx.save();
var ctxLeft = -( pug.width / 2 );
var ctxTop = -( pug.height / 2 );
ctx.translate( ctxLeft, ctxTop );
ctx.scale(scaleXTo1, scaleYTo1);
ctx.beginPath();
console.log(points)
ctx.moveTo(points[0][0] - pug.oCoords.tl.x, points[0][1] - pug.oCoords.tl.y);
for (var i=1; i < points.length; i++){
ctx.lineTo(points[i][0] - pug.oCoords.tl.x, points[i][1] - pug.oCoords.tl.y);
}
ctx.closePath();
ctx.restore();
};
clipYellowRect.remove();
clipRedRect.remove();
canvas.renderAll();
}
Hopefully it will help you.
Related
I loaded multiple objects from svg by following code:
var canvas = new fabric.Canvas('drawing');
fabric.loadSVGFromURL('images/circle.svg', function(objects) {
canvas.add.apply(canvas, objects);
canvas.forEachObject(function(o){ o.hasBorders = o.hasControls = false;
});
canvas.renderAll();
});
Now I want to free draw only inside one object(like the image below).How can I achieve that using fabric.js?
You can mask the canvas (using canvas.clipTo) and make it match your SVG form. If it is a circle as in your example image it would be simple.
See the following example:
// define a drawing canvas
const canvas = new fabric.Canvas(
'drawing',
{ isDrawingMode: true }
);
canvas.freeDrawingBrush.color = 'red'
// create a circle (here you could load your svg circle instead)
const circle = new fabric.Circle({
top: 25,
left: 25,
radius: 50,
fill: 'transparent',
stroke: 'black'
});
// create the clipping mask using the circle coordinates
canvas.clipTo = function (ctx) {
ctx.arc(
circle.top + circle.radius,
circle.left + circle.radius,
circle.radius + 1, // +1px for the circle stroke
circle.radius + 1,
Math.PI*2,
true
)
}
// add the circle to the canvas
canvas.add(circle);
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.5/fabric.min.js"></script>
<canvas id="drawing" width="600" height="600"></canvas>
Is there anyway to add shadow to transparent objects in FabricJS? I've used set fill transparent and after that setshadow. But normally setshadow can't be seen because object is transparent.
You can accomplish this using a clip path when drawing the object with the shadow. To do this with FabricJS you can subclass the object type you're generating the shadow from, and override the _render function to set a clip path that includes the area where the shadow falls but excludes the object itself. Ideally this reuses the code that actually draws the object.
fabric.BoxShadow = fabric.util.createClass(fabric.Rect, {
shadowColor: undefined,
shadowBlur: 0,
shadowOffsetX: 0,
shadowOffsetY: 0,
initialize(options) {
this.callSuper('initialize', options);
// Note: the way I have implemented this, the shadow settings cannot be changed after the object has been created.
this._shadow = new fabric.Shadow({
color: this.shadowColor,
blur: this.shadowBlur,
offsetX: this.shadowOffsetX,
offsetY: this.shadowOffsetY
});
},
_render: function(ctx) {
ctx.save();
// set clip path
let [offsetX, offsetY, blur] = [this.shadowOffsetX,
this.shadowOffsetY,
this.shadowBlur
];
let [top, left] = [this.width / -2, this.height / -2];
let region = new Path2D();
// The outer rectangle for our clipping path completely encompases the object and its shadow
let bounds = {
t: Math.min(top, top + offsetY - blur),
l: Math.min(left, left + offsetX - blur),
b: Math.max(top + this.height, top + this.height + offsetY + blur),
r: Math.max(left + this.width, left + this.width + offsetX + blur),
};
region.rect(bounds.l, bounds.t, bounds.r - bounds.l, bounds.b - bounds.t);
// now we subtract the actual object from our clipping path
// Note: we have to add beginPath function because the base class render code is going to treat this likc a CanvasRenderingContext2D instead of a Path2D
region.beginPath = function() { };
this.callSuper('_render', region);
ctx.clip(region, "evenodd");
// Fabric draws shadows, oddly enough, around the entire area rendered within this function. I haven't figured out the correct function to override to get our clip path to work with the normal fabric rendering pipeline
this.shadow = this._shadow;
// leverage the FabricJS shadow sizing logic
this._setShadow(ctx);
this.callSuper('_render', ctx);
this.shadow = undefined;
ctx.restore();
},
_renderPaintInOrder: function(ctx) {
if (ctx instanceof CanvasRenderingContext2D) {
this.callSuper('_renderPaintInOrder', ctx);
}
}
});
(function() {
let canvas = new fabric.Canvas('c');
fabric.Object.prototype.transparentCorners = false;
canvas.add(new fabric.Rect({
top: 40,
left: 40,
width: 100,
height: 100,
fill: 'lightblue'
}));
canvas.add(
new fabric.BoxShadow({
rx: 10,
top: 10,
left: 10,
width: 100,
height: 100,
shadowColor: 'black',
shadowBlur: 4,
shadowOffsetX: 3,
shadowOffsetY: 3
})
);
canvas.setWidth(document.body.clientWidth);
canvas.setHeight(document.body.clientHeight);
})();
html {
height: 100%;
}
body {
height: 100%;
}
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.7.0/fabric.js"></script>
</head>
<body>
<canvas id="c"></canvas>
</body>
</html>
I don't think the FabricJS API has a shadow-without-shape option.
But you can easily create the shadow-only using a native html5 canvas and then use that native canvas as an image source for a Fabric.Image object.
With native html5 canvas you can create a shadow without it's source shape like this:
Draw the shadowed shape,
Use compositing to "erase" the shape -- leaving just it's shadow
Example code drawing shadow-only on a native html5 canvas:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var shadowBlur=8;
var x=shadowBlur;
var y=shadowBlur;
var width=100;
var height=65;
canvas.width=width+shadowBlur*2;
canvas.height=height+shadowBlur*2;
// draw the shadowed shape
ctx.shadowColor='black';
ctx.shadowBlur=8;
ctx.fillRect(x-ctx.shadowOffsetX,y,width,height);
// always clean up! -- undo shadowing
ctx.shadowColor='rgba(0,0,0,0';
// use compositing to remove the shape
// (leaving just the shadow);
ctx.globalCompositeOperation='destination-out';
ctx.fillRect(x,y,width,height);
// always clean up! -- set compositing to default
ctx.globalCompositeOperation='source-over';
body{ background-color:white; }
#canvas{border:1px solid red; }
<canvas id="canvas" width=512 height=512></canvas>
Example creating a Fabric.Image using native html5 canvas as an image source:
// where "canvas" is a reference to an html5 canvas element
var myFabricImage=new fabric.Image(canvas, { left:0, top:0 });
I am writing code to maintain same strokeWidth across all the objects in Fabricjs.
I am able to successfully maintain strokeWidth for normal Objects , let it be rectangle or ellipse(I wrote code to maintain both).
But when I use group , I am unable to maintain the strokeWidth.
Here's the fiddle.
Steps to reproduce the issue ?
1)Open above fiddle link
2)resize the circle , check the size of border (thickness of border remains the same on re-sizing)
3)Now resize the rectangle and text(group) , expected result is thickness of border must be same throughout but that doesn't happens.
Code :
`
var gCanvas = new fabric.Canvas('canvDraw');
gCanvas.setWidth(700);
gCanvas.setHeight(700);
var text = new fabric.Text('test', { fontSize: 30, top: 100, left : 100, fill : 'red'});
// add some shapes - these are examples, others should work too
var myRectangle = new fabric.Rect({
left: 100,
top: 100,
fill: '#999999',
width: 120,
height: 120,
strokeWidth: 3,
fill: '',
stroke: '#000000'
});
var group = new fabric.Group([ myRectangle, text ], {borderColor: 'black', cornerColor: 'green', lockScalingFlip : true});
gCanvas.add(group);
var myEllipse = new fabric.Ellipse({
top: 250,
left: 100,
rx: 75,
ry: 50,
fill: '',
stroke: '#000000',
strokeWidth: 3
});
gCanvas.add(myEllipse);
gCanvas.observe('object:scaling', function (e) {
e.target.resizeToScale();
});
fabric.Object.prototype.resizeToScale = function () {
// resizes an object that has been scaled (e.g. by manipulating the handles), setting scale to 1 and recalculating bounding box where necessary
switch (this.type) {
case "ellipse":
this.rx *= this.scaleX;
this.ry *= this.scaleY;
this.width = this.rx * 2;
this.height = this.ry * 2;
this.scaleX = 1;
this.scaleY = 1;
break;
case "rect":
this.width *= this.scaleX;
this.height *= this.scaleY;
this.scaleX = 1;
this.scaleY = 1;
default:
break;
}
}
`
this approach will not work for all kind of shapes. when facing text or polygons you cannot recalculate everything.
you can do something like that:
fabric.Object.prototype.resizeToScale = function () {
if (this.type !=='group') {
this.strokeWidth = this._origStrokeWidth / Math.max(this.scaleX, this.scaleY);
}
else {
this._objects.forEach( function(obj){
console.log(obj);
obj.strokeWidth = obj._origStrokeWidth / Math.max(obj.group.scaleX, obj.group.scaleY);
});
}
}
if you prefer the effect of your solution (border is always uniform) put this line of code in the default case of your switch construct to handle all the types for wich you cannot find a resizing solution.
edit i added group handling.
The point is to make smaller strokewidth when the group / object scale.
Because when you will have polygons and polylines and paths, changing width / height /radius will not help.
http://jsfiddle.net/y344vs5s/4/
The problem is to update the actual object.width, object.height and keep object.scaleX = 1 and object.scaleY = 1 when using the visual controls on the canvas.
The origin of the problem is when manipulating the object using controls, fabric.js changes the scale of the object, as well as scaling the stroke of paths, which I would like to be of the same width always.
So I would like to make it more like Adobe Illustrator-like, and not scale the width of the stroke along with the width of the rectalngular, for example.
I have found a solution to a question formulated in a different manner here:
Rect with stroke, the stroke line is mis-transformed when scaled
The idea is to calculate the new would-be width and height using the new scale factors, set the new dimensions and reset the scale factors to 1.
Here's the code example from that answer:
el.on({
'scaling': function(e) {
var obj = this,
w = obj.width * obj.scaleX,
h = obj.height * obj.scaleY,
s = obj.strokeWidth;
obj.set({
'height' : h,
'width' : w,
'scaleX' : 1,
'scaleY' : 1
});
}
});
From Fabric.js version 2.7.0 you can enable a strokeUniform property on the object this will always match the exact pixel size entered for stroke width.
var circle2 = new fabric.Circle({
radius: 65,
fill: '#4FC3F7',
left: 110,
opacity: 0.7,
stroke: 'blue',
strokeWidth: 3,
strokeUniform: true
});
http://fabricjs.com/stroke-uniform
Having trouble getting the modified rotational angle of fabic.js object retaliative to is original angle/position.
I'm using .getAngle(), If the object is rotated more than 360 degrees or rotated back and forth I'm having trouble converting this back to an angle in degrees relative to it original position/rotation.
var canvas = new fabric.Canvas('canvas');
//global canvas setting
canvas.selection = false;
canvas.setDimensions({
width: 500,
height: 310
});
//Canvas Objets
// create a rectangle with angle=45
var rect = new fabric.Rect({
left: 100,
top: 100,
fill: 'red',
width: 40,
height: 40,
lockUniScaling: true,
centeredRotation: true
});
canvas.add(rect);
//Object modification event
canvas.on('object:modified', function(e) {
var activeObject = e.target;
document.getElementById('result').value = activeObject.getAngle();
});
I've setup a fiddle showing the default output http://jsfiddle.net/1db5g7us/
I'm assuming in need to do some calculation on the result, but can't figure out what.
Just solved this one, all i needed to do was use the modulus operator to get the rotation relative to its original position rather than the total rotated angle.
activeObject = activeObject%360;
update the fiddle: http://jsfiddle.net/1db5g7us/