I have 3 rectangles on top of eachother like so:
new Fabric.Rect({
width: 200 - index * 30,
height: 20,
hasBorders: false,
selectable: false,
hasControls: false
});
and then I have a click event which detects clicks NEAR (not on the rectangle) the rectangles and makes the top rectangle (highest one of the stack of 3) selectable (to drag it):
var first = this.first().shape; // Fabric.Rect
canvas.setActiveObject(first);
However, this does not set the object on the cursor, to drag the object.
How can I make it so the object is selected, immediately moved to the cursor and enabled to be dragged around once the click event fires?
This should get you fairly close, if I understood you correctly.
Click anywhere inside the black square of the canvas and outside the red object.
var canvas = new fabric.Canvas('c', {
selection: false,
});
var rectangle = new fabric.Rect({
fill: 'red',
left: 10,
top: 10,
width: 100,
height: 100 //,
//padding: 50
});
canvas.on('mouse:down', function(env) {
var x = env.e.offsetX;
var y = env.e.offsetY;
rectangle.setLeft(x - rectangle.width / 2);
rectangle.setTop(y - rectangle.height / 2);
canvas.setActiveObject(rectangle);
rectangle.setCoords();
canvas.renderAll();
canvas.on('mouse:move', function(env) {
var x = env.e.offsetX;
var y = env.e.offsetY;
rectangle.setLeft(x - rectangle.width / 2);
rectangle.setTop(y - rectangle.height / 2);
rectangle.setCoords();
canvas.renderAll();
});
canvas.on('mouse:up', function(env) {
canvas.off('mouse:move');
});
});
canvas.add(rectangle);
canvas.renderAll();
#c {
border: 1px solid black;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js"></script>
<canvas id="c" width="200" height="200"></canvas>
I intentionally commented out padding on the rectangle, but left it in the code, in case you wanted to use that as your NEAR logic instead of what you already have. If you do choose to use padding as your NEAR logic you will then need to change the on canvas mouse:down event to an on canvas object:selected event.
Also, if you haven't done so already, you might like to take a close look at this Objects Bounding Rectangles example for some further ideas for your NEAR logic, http://fabricjs.com/bounding-rectangle.
Any-who, let me know how you get on, matey!
Related
Next code create triangles on canvas, if you are not clicking over an existing triangle. And you may save all elements to JSON with clicking on "save" button.Then preview the JSON variable in console.
My problem is that after resizing of an object, height and width are not updated in Json, when clicked on save again.
To resize the triangle You have to click on it. Then grab one of the anchor rectangles and drag it from the center of triangle.
What action must I perform to have also new height and width of the object?
Next is code snippet on jsFfidle: https://jsfiddle.net/ug7p9myc/76/
var canvas = new fabric.Canvas('c5');
function some1(x1, y2) {
var c = new fabric.Triangle({
left: posX2,
top: posY2,
width: 15,
height: 25,
strokeWidth: 3,
fill: '#666',
stroke: '#666'
});
canvas.add(c);
}
var posX2, posY2;
canvas.on('mouse:down', function(e) {
var pointer = canvas.getPointer(e.e);
posX2 = pointer.x;
posY2 = pointer.y;
if (e.target) {} else {
some1(posY2, posY2);
}
});
function saveJsonF() {
var jsonToPHP = JSON.stringify(canvas.toObject());
console.log(jsonToPHP);
}
document.getElementById("saveJsonID").onclick = saveJsonF;
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.22/fabric.min.js"></script>
<input type="button" class="Btn1" id="saveJsonID" value="Save" /></br><br>
<canvas id="c5" width="1060" height="550" style="border: 1px solid black"></canvas>
Use getScaledWidth and getScaledHeight to get the transformed values. If you scale an object, its scaleX and scaleY value changes.
i use zoomtopoint and zoom to object. but not working with background.
I want to zoom in on the object and the background. How can i ?
Example :
object size : 100x100 not zoom.
after zoom object size :100x100
after zoom and The grid remained the same.
zoom event
document.addEventListener('wheel', function(event) {
var evt = window.event || event;
var delta = evt.detail? evt.detail*(-120) : evt.wheelDelta;
var curZoom = canvas.getZoom();
var newZoom = curZoom + delta / 4000;
var x = event.offsetX;
var y = event.offsetY;
canvas.zoomToPoint({ x: x, y: y }, newZoom);
if(event != null)event.preventDefault();
return false;
canvas.calcOffset();
}, false);
grid code:
canvas.setBackgroundColor({source: src, repeat: 'repeat'}, canvas.renderAll.bind(canvas), function () {
canvas.renderAll();
proceed();
});
EDİT
#canvas-background { display: inline-block; position: absolute; top: 0; right: 0; }
but i dont use css.
Background image
Thank you
Sorry, i cant speak english well.
Relevant code is below (and the rest is in the JSFiddle), note the canvas size and CSS container trick used to allow zooming out.
Example : object size : 100x100 not zoom.
after zoom object size :100x100
after zoom and The grid is no longer the same.
fabric.Image.fromURL('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAIAAACRXR/mAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAASdEVYdFNvZnR3YXJlAEdyZWVuc2hvdF5VCAUAAADLSURBVFhH7ZnBCoMwEET9/68URBHSNj0UolFoI+aQickKlT05jz0MGQIPkb2kadu3ta42ff/MTtLRazct55bajOMjO0lHr920vnWMMTGV0GuphVALoRaiqNV1dq4TLsdUIrTe+z0fw+ndmEo0w/D61AmXYyqh1179WjGVuNLyl0eohVALuZ8Wtzwgt9zyiNxSC6EWQi1EUYtbHpBbbnlEbqmFUAuhFqKoxS0PyC23PCK31EKohVAL0dXK3vLSOX0TnKZ1z8fw/3uiW37L27QIZwrV4gAAAABJRU5ErkJggg==', function(img) {
var patternSourceCanvas = new fabric.StaticCanvas();
patternSourceCanvas.add(img);
var pattern = new fabric.Pattern({
source: function() {
patternSourceCanvas.setDimensions({
width: img.getWidth(),
height: img.getHeight()
});
return patternSourceCanvas.getElement();
},
repeat: 'repeat'
});
var background = new fabric.Rect({
width: canvas.getWidth(),
height: canvas.getHeight(),
fill: pattern,
selectable: false
});
canvas.add(background, rectangle);
canvas.renderAll();
});
Here's a working JSFiddle, https://jsfiddle.net/rekrah/86t2b8bs/.
Hope this helps.
UPDATE:
#forguta also wanted to ensure objects didn't go behind the background when sendToBack() was run. Made "repeated" background image into one image so setBackgroundImage() could be used (image size only increased to 64K and I'm sure could be compressed further).
Simpler code:
canvas.setBackgroundImage('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAACcQAAAnECAIAAAChEWJqAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4QMDDwYflNda9wAAIABJREFUeNrs2TGO67qWhlHSotSFm7z5z+4NoQsoXJbFs8HObYoGbJxmslYk4JfgD053/u9///............', canvas.renderAll.bind(canvas), {
// Needed to position backgroundImage at 0/0
originX: 'left',
originY: 'top'
});
Here's an updated working JSFiddle, https://jsfiddle.net/rekrah/u0srdsdr/.
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.
Hello I use fabricjs to play with the html canvas.
I create the canvas and i add group of objects on it.
On a group of objects, I need to keep fixed width & height for some objects while I scale the object.
I use the 'object:scaling' event to get the active object when it changes size, I read each object of the group and I assign element[i].set({'radius':5}) on the group objects that I want to be unchanged.
But the result is that , all the group object to resize.
I show you the snippet of the object:scaling event :
canvas.on('object:scaling',function(e){
var activeObject1 = e.target;
var elements = e.target._objects;
var count_elements = elements.length;
for(var i = 0; i < count_elements; i++) {
var type = elements[i].typeCircle;
if(type == "parts"){
//elements[i].set({"radius":8,"fill":"#abcde2","stroke":"#367827"});
//elements[i].set('radius',8);
/*elements[i].setWidth(16);
elements[i].setHeight(16);
elements[i].currentWidth = 16;
elements[i].currentHeight = 16;
elements[i].scaleX = 1;
elements[i].scaleY = 1;
console.log(elements[i]);
canvas.renderAll();*/
}
}
});
What should I write into the for loop to keep fixed size on some objects?
everything that I used above, they don't work except for the "fill":"#abcde2","stroke":"#367827"
If anyone has faced something similar on fabricjs, please let me know .
You must use setScaleX() and setScaleY() methods.
Here is an example...
var Rect = new fabric.Rect({
width: 200,
height: 200,
top: 100,
left: 100,
fill: 'rgba(255,0,0,0.5)',
stroke: '#000',
strokeWidth: 1,
});
var Circle = new fabric.Circle({
left: 100,
top: 100,
fill: '#FF00FF',
stroke: 'red',
radius: 100,
opacity: 1,
});
var Group = new fabric.Group([Rect, Circle])
canvas.add(Group)
canvas.on({
'object:scaling': onChange
})
function onChange(obj) {
var circle = obj.target.item(1),
group = obj.target,
scaleX = circle.width / group.getWidth(),
scaleY = circle.height / group.getHeight();
circle.setScaleX(scaleX);
circle.setScaleY(scaleY);
}
JSFIDDLE
Using fabricjs2 to stop scaling of a text item I have modified Rafik Avtoyan's function to work well. I have locked Y scaling for my group so you will have to add this if required.
function handleScalingEvent(obj) {
var text = obj.target.item(1),
group = obj.target,
scaleX = group.width / (group.width * group.scaleX);
text.set('scaleX', scaleX);
}
Best way to make the objects the same size is to divide desired width by object width. For example, if you want all added objects to be 256px the code will look this way:
function selectImage(imagePath){
fabric.Image.fromURL(imagePath, function(oImg) {
canvas.add(oImg);
let zoom = 256 / oImg.width;
oImg.set({ scaleX: zoom, scaleY: zoom, });
oImg.center();
});
}
In the case when the image will be 64px it will scale it by 4 to 256px and in case the image is 512px it will scale it by 0.5 which will make the image smaller to 256px.
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/