Version
4.2.0
Test Case
https://jsfiddle.net/dellvolk/c8zas7th/12/
let optObj = {
width: 300,
height: 300,
backgroundColor: "rgba(255,255,0,0.5)",
}
let canvas = new fabric.Canvas('c', optObj);
const stroke = {
stroke: 'red',
strokeWidth: 10,
}
const rect1 = new fabric.Rect({
left: 30,
top: 30,
...stroke,
width: 100,
height: 100,
fill: 'blue',
padding: -stroke.strokeWidth,
borderColor: '#000',
})
const rect2 = new fabric.Rect({
left: 130,
top: 130,
...stroke,
width: 100,
height: 100,
fill: 'green',
padding: -stroke.strokeWidth,
borderColor: '#000',
})
fabric.Object.prototype.padding = -10;
canvas.add(rect1);
canvas.add(rect2);
Expected Behavior
I need that when objects form group padding remained. I don't need to set a padding for the group. Only for elements in this group. That the stroke of the group remained as it is, and the black stroke of the elements of the group was like the padding of the elements themselves
Actual Behavior
Padding in objects is -10, but when they form group, the padding changes to 0
The method that handles the border size calculation for objects in a group is drawBordersInGroup (see http://fabricjs.com/docs/fabric.Object.html#drawBordersInGroup).
The following should work as a drop-in replacement for this method in order to factor padding into the size calculation:
https://jsfiddle.net/melchiar/bw384o2n/
//drop in replacement for drawBordersInGroup method
fabric.Object.prototype.drawBordersInGroup = function(ctx, options, styleOverride) {
styleOverride = styleOverride || {};
var bbox = fabric.util.sizeAfterTransform(this.width, this.height, options),
strokeWidth = this.strokeWidth,
strokeUniform = this.strokeUniform,
//borderScaleFactor = this.borderScaleFactor,
//adds object padding to border scale calculation
borderScaleFactor = this.borderScaleFactor + this.padding * 2,
width =
bbox.x + strokeWidth * (strokeUniform ? this.canvas.getZoom() : options.scaleX) + borderScaleFactor,
height =
bbox.y + strokeWidth * (strokeUniform ? this.canvas.getZoom() : options.scaleY) + borderScaleFactor;
ctx.save();
this._setLineDash(ctx, styleOverride.borderDashArray || this.borderDashArray, null);
ctx.strokeStyle = styleOverride.borderColor || this.borderColor;
ctx.strokeRect(
-width / 2,
-height / 2,
width,
height
);
ctx.restore();
return this;
};
Related
I'm trying to draw rectangle with rounded corners but when setting negative width or height I'm getting a wrong shape like this
How to have the correct shape (the top left one in the gif) regardless of the start point and the draw direction?
canvas.on('mouse:down', (e) => {
const roundedRect = new fabric.Rect( {
top: e.pointer.y,
left: e.pointer.x,
width: 0,
height: 0,
stroke: 'black',
strokeWidth: 3,
rx: 10,
ry: 10,
fill: 'transparent',
hasControls: false,
});
canvas.add(roundedRect);
canvas.setActiveObject(roundedRect);
});
canvas.on('mouse:move', (e) => {
const pointer = e.pointer;
const activeObj = canvas.getActiveObject();
let height = pointer.y - activeObj.top;
let width = pointer.x - activeObj.left;
activeObj.set({ height: height, width: width});
activeObj.setCoords();
});
In the below Image I have three boxes in the canvas and there are three buttons at the bottom of the image. Whenever I click a button, the corresponding object in the canvas gets selected(i,e, when I click the green button, green rectangle in the canvas, gets selected).
My requirement is to highlight only the selected portion and other portion of the canvas should be grayed out. (Ex: If I click the green button green rectangle should be selected and other portion should be overlayed with a gray background).
Js Fiddle Link: https://jsfiddle.net/rnvs2hdk/1/
var canvas = new fabric.Canvas('c');
canvas.backgroundColor = 'yellow';
var li= []
canvas.renderAll();
fabric.Image.fromURL('http://fabricjs.com/assets/pug_small.jpg', function(myImg) {
var img1 = myImg.set({ left: 0, top: 0 ,width:400,height:500});
canvas.add(img1);
var green = new fabric.Rect({
left: 50,
top: 50,
width: 50,
height: 50,
fill: 'rgba(255,255,255,1)',
stroke: 'rgba(34,177,76,1)',
strokeWidth: 5,
name:"green"
});
var yellow = new fabric.Rect({
left: 150,
top: 50,
width: 50,
height: 50,
fill: 'rgba(255,255,255,1)',
stroke: 'rgba(255,255,0,1)',
strokeWidth: 5,
name:"yellow"
});
var red = new fabric.Rect({
left: 250,
top: 50,
width: 50,
height: 50,
fill: 'rgba(255,255,255,1)',
stroke: 'rgba(255,0,0,1)',
strokeWidth: 5,
name:"red"
});
canvas.add(green, yellow,red);
li.push(green);
li.push(yellow);
li.push(red);
li.some(v=>{
var btn = document.createElement("BUTTON"); // Create a <button> elem
btn.innerHTML = v.name;
btn.addEventListener('click',function(e){
var name = e.target
if(name.innerText == "green"){
canvas.setActiveObject(li[0]);
}
if(name.innerText == "yellow"){
canvas.setActiveObject(li[1]);
}
if(name.innerText == "red"){
canvas.setActiveObject(li[2]);
}
});// Insert text
document.body.appendChild(btn);
});
console.log(li);
});
Expected Result:(example)
Here's my solution. Using the after:render event, you can perform canvas draw actions over each frame after it is rendered. This approach has the benefit of avoiding having to create and destroy fabric objects as needed which is an expensive operation.
Be sure to call the .setCoords() method during actions like scaling and moving so that objects will update their position information while performing these actions.
var canvas = new fabric.Canvas('c');
canvas.backgroundColor = 'yellow';
var li = [];
canvas.renderAll();
fabric.Image.fromURL('http://fabricjs.com/assets/pug_small.jpg', function(myImg) {
var img1 = myImg.set({
left: 0,
top: 0,
width: 400,
height: 500
});
canvas.add(img1);
var green = new fabric.Rect({
left: 50,
top: 50,
width: 50,
height: 50,
fill: 'rgba(255,255,255,1)',
stroke: 'rgba(34,177,76,1)',
strokeWidth: 5,
name: "green",
hasRotatingPoint: false
});
var yellow = new fabric.Rect({
left: 150,
top: 50,
width: 50,
height: 50,
fill: 'rgba(255,255,255,1)',
stroke: 'rgba(255,255,0,1)',
strokeWidth: 5,
name: "yellow",
hasRotatingPoint: false
});
var red = new fabric.Rect({
left: 250,
top: 50,
width: 50,
height: 50,
fill: 'rgba(255,255,255,1)',
stroke: 'rgba(255,0,0,1)',
strokeWidth: 5,
name: "red",
hasRotatingPoint: false
});
canvas.add(green, yellow, red);
li.push(green);
li.push(yellow);
li.push(red);
li.some(v => {
var btn = document.createElement("BUTTON"); // Create a <button> elem
btn.innerHTML = v.name;
btn.addEventListener('click', function(e) {
var name = e.target
if (name.innerText == "green") {
canvas.setActiveObject(li[0]);
}
if (name.innerText == "yellow") {
canvas.setActiveObject(li[1]);
}
if (name.innerText == "red") {
canvas.setActiveObject(li[2]);
}
}); // Insert text
document.body.appendChild(btn);
});
console.log(li);
});
canvas.on({
'object:moving': function(e) {
//makes objects update their coordinates while being moved
e.target.setCoords();
},
'object:scaling': function(e) {
//makes objects update their coordinates while being scaled
e.target.setCoords();
}
});
//the after:render event allows you to perform a draw function on each frame after it is rendered
canvas.on('after:render', function() {
var ctx = canvas.contextContainer,
obj = canvas.getActiveObject();
if (obj) {
//set the fill color of the overlay
ctx.fillStyle = "rgba(0, 0, 0, 0.3)";
var bound = obj.getBoundingRect();
ctx.beginPath();
//draw rectangle to the left of the selection
ctx.rect(0, 0, bound.left, canvas.height);
//draw rectangle to the right of the selection
ctx.rect(bound.left + bound.width, 0, canvas.width - bound.left - bound.width, canvas.height);
//draw rectangle above the selection
ctx.rect(bound.left, 0, bound.width, bound.top);
//draw rectangle below the selection
ctx.rect(bound.left, bound.top + bound.height, bound.width, canvas.height - bound.top - bound.height)
ctx.fill();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>
<canvas id="c" width="400" height="400"></canvas>
<div id="bt"></div>
I have Accomplished this creating 4 more rectangles around the actual rectangle. I have grayed out the outer rectangles so it gives the overlay effect. Also, I will delete all the rectangles before creating a new one.
let blankColor = "rgba(0,0,0,0)";
let grayOut = "rgba(0,0,0,0.4)";
let rect = createRect(x, y, width, height, 1, blankColor);
let rect1 = createRect(0, 0, getViewPortDimensions()[0], y, 0, grayOut);
let rect2 = createRect(0, y + height, getViewPortDimensions()[0], getViewPortDimensions()[1] - (y + height), 0, grayOut);
let rect3 = createRect(0, y, x, height, 0, grayOut);
let rect4 = createRect(x + width, y, getViewPortDimensions()[0] - (x + width), height, 0, grayOut);
state.canvas.add(rect, rect1, rect2, rect3, rect4);
Deleting the already drawn rectangle:
state.canvas.forEachObject((o, index) => {
if (index != 0) {
state.canvas.remove(o);
}
})
I'am trying to clip the FabricJS rect shape to the polygon shape. The clipping works okay until the polygon shape which need to be clipped is now scaled. After this there is some weird offset that is caused by the polygon clipping.
Can anyone help me how can i fix the function to prevent the polygon offset issue when clip object is scaled.
This is how it looks before scalling. The clipping works fine
Image => https://i.imgur.com/Eop2YJh.png
And then there is the problem when the polygon is scaled.
2: Image => https://i.imgur.com/ICkP8SG.png
Here is the code on fiddle with the clipping function
https://jsfiddle.net/0xpvc9uq/
So if there is anyone who knows whats the point and how can I fix it I would appriciate it.
Thx
var canvas = new fabric.Canvas('c');
var rect1 = new fabric.Rect({
left: 0, top: 0,
width: 900, height: 900,
fill: 'blue',
selectable: false,
clipTo: clipRegion,
scaleX: 1.5,
scaleY: 1.5
});
var clipPoly = new fabric.Polygon([
{ x: 180, y: 10 },
{ x: 300, y: 50 },
{ x: 300, y: 180 },
{ x: 180, y: 220 }
], {
originX: 'left',
originY: 'top',
left: 180,
top: 10,
fill: 'transparent', /* use transparent for no fill */
strokeWidth: 0,
selectable: false,
strokeWidth: 1,
stroke: "red",
scaleX: 1.3,
scaleY: 1.3
});
canvas.add(rect1, clipPoly);
function clipRegion (ctx) {
rect1.setCoords();
const clipObj = clipPoly;
const scaleXTo1 = (1 / rect1.scaleX);
const scaleYTo1 = (1 / rect1.scaleY);
ctx.save();
const ctxLeft = -( rect1.width / 2 ) - clipObj.strokeWidth - rect1.strokeWidth;
const ctxTop = -( rect1.height / 2 ) - clipObj.strokeWidth - rect1.strokeWidth;
ctx.translate( ctxLeft, ctxTop );
ctx.scale(scaleXTo1, scaleYTo1);
ctx.rotate((rect1.angle * -1) * (Math.PI / 180));
ctx.beginPath();
const matrix = clipPoly.calcTransformMatrix();
let points = [];
clipObj.points.forEach( (point) => {
points.push({
x: ((point.x * matrix[0]) + (clipObj.strokeWidth * clipObj.scaleX)) - rect1.oCoords.tl.x,
y: ((point.y * matrix[3]) + (clipObj.strokeWidth * clipObj.scaleY)) - rect1.oCoords.tl.y
});
});
ctx.moveTo(points[0].x, points[0].y);
points.forEach((point) => {
ctx.lineTo(point.x, point.y);
});
ctx.lineTo(points[0].x, points[0].y);
ctx.closePath();
ctx.restore();
}
I discovered that there is also another approach that can be used and that solves all the problem.
The clipRegion function now looks like:
function clipRegion (ctx) {
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
clipPoly.render(ctx);
ctx.restore();
}
Which makes the rendering okay. If still anyone have other way to fix the above problem, I would like to see the answer
Any suggestion on select multi objects on canvas mouse click? not all object, I want to select objects that overlay on the point.
For my knowledge, the target on mouse event is always the top most object only.
I had tried to bind event on object, but it wont fired for those at the back side.
I had tried select based on item size and height, but it is not working perfectly after rotate.
var canvas = this.__canvas = new fabric.Canvas('c', {
enableRetinaScaling: false
});
function LoopOnObjects(e) {
var mouse = canvas.getPointer(e.e, false);
var x = Math.ceil(mouse.x);
var y = Math.ceil(mouse.y);
var count = 0;
canvas.getObjects().forEach(function(object, index){
if(CheckObjectWithin(object, x, y)) {
count++;
}
});
alert("ya, there is " + count + " objects touch on click");
}
function CheckObjectWithin(object, x, y) {
var objectBoundRect = object.getBoundingRect(true);
var widthRange = objectBoundRect.width;
var heightRange = objectBoundRect.height;
if (x > objectBoundRect.left && x < objectBoundRect.left + widthRange) {
if (y > objectBoundRect.top && y < objectBoundRect.top + heightRange) {
return true;
}
}
return false;
}
function GetElement(e) {
LoopOnObjects(e);
}
canvas.on("mouse:up", GetElement);
canvas.add(new fabric.Rect({
width: 100, height: 100, left: 100, top: 20, angle: -10,
fill: 'rgba(0,200,0,0.5)'
}));
canvas.add(new fabric.Rect({
width: 50, height: 100, left: 220, top: 80, angle: 45,
stroke: '#eee', strokeWidth: 10,
fill: 'rgba(0,0,200,0.5)'
}));
canvas.add(new fabric.Circle({
radius: 50, left: 220, top: 175, fill: '#aac'
}));
template for testing
Actually, there is already a library method for that: fabric.Object.prototype.containsPoint(). It works with rotate, but keep in mind that the point is checked against the bounding box, not the visible shape (e.g. circle shape still has a rectangular bounding box).
var canvas = this.__canvas = new fabric.Canvas('c');
function loopOnObjects(e) {
var mouse = canvas.getPointer(e.e, false);
var point = new fabric.Point(mouse.x, mouse.y)
var count = 0;
canvas.getObjects().forEach(function(object, index){
if (object.containsPoint(point)) {
count++;
}
});
}
function getElement(e) {
loopOnObjects(e);
}
canvas.on("mouse:down", getElement);
canvas.add(new fabric.Rect({
width: 100, height: 100, left: 100, top: 20, angle: -10,
fill: 'rgba(0,200,0,0.5)'
}));
canvas.add(new fabric.Rect({
width: 50, height: 100, left: 220, top: 80, angle: 45,
stroke: '#eee', strokeWidth: 10,
fill: 'rgba(0,0,200,0.5)'
}));
canvas.add(new fabric.Circle({
radius: 50, left: 220, top: 175, fill: '#aac'
}));
#c {
border: 1px black solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.22/fabric.min.js"></script>
<canvas id="c" width="500" height="300"></canvas>
Here is the jsfiddle.
I want to limit the maximum height/width of the object when you are resizing it.
Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://raw.github.com/kangax/fabric.js/master/dist/all.js"></script>
</head>
<body>
<canvas id="c" width="300" height="300" style="border:1px solid #ccc"></canvas>
<script>
(function() {
var canvas = new fabric.Canvas('c');
canvas.add(new fabric.Rect({ width: 50, height: 50, fill: 'red', top: 100, left: 100 }));
canvas.add(new fabric.Rect({ width: 30, height: 30, fill: 'green', top: 50, left: 50 }));
})();
</script>
</body>
</html>
When scaling fabric Objects, the scaleX and scaleY properties are updated to reflect the new scaled size of the object. So the actual width of a rect with an initial width of 50 when scaled 2x will be 100.
What you need to do is figure out the maximum scale allowed for your shape given it's maxHeight or maxWidth. That's calculated by dividing the maximum dimension by the initial dimension.
Here's an example of how to implement maximum sizes for objects
var canvas = new fabric.Canvas("c");
var rect1 = new fabric.Rect({ width: 50, height: 50, fill: 'red', top: 100, left: 100});
var rect2 = new fabric.Rect({ width: 30, height: 30, fill: 'green', top: 50, left: 50 });
// add custom properties maxWidth and maxHeight to the rect
rect1.set({maxWidth:100, maxHeight:120});
canvas.observe("object:scaling", function(e){
var shape = e.target
, maxWidth = shape.get("maxWidth")
, maxHeight = shape.get("maxHeight")
, actualWidth = shape.scaleX * shape.width
, actualHeight = shape.scaleY * shape.height;
if(!isNaN(maxWidth) && actualWidth >= maxWidth){
// dividing maxWidth by the shape.width gives us our 'max scale'
shape.set({scaleX: maxWidth/shape.width})
}
if(!isNaN(maxHeight) && actualHeight >= maxHeight){
shape.set({scaleY: maxHeight/shape.height})
}
console.log("width:" + (shape.width * shape.scaleX) + " height:" + (shape.height * shape.scaleY));
});
Works with most fabric objects.. but you want to get the ratio of your object, for maxWidth you can copy this... for maxHeight reverse it.
fabric.Image.fromURL(photo, function(image) {
//console.log(image.width, image.height);
var heightRatio = image.height / image.width;
var maxWidth = 100;
image.set({
left: canvasDimensions.width / 2,//coord.left,
top: canvasDimensions.height / 2, //coord.top,
angle: 0,
width: maxWidth,
height: maxWidth * heightRatio
})
//.scale(getRandomNum(minScale, maxScale))
.setCoords();
canvas.add(image);
})