Can't get overlay to resize fabric.js? - javascript

I've been able to get the canvas to resize, and also include touch events. But for some reason, I can't get the overlay image to fill the canvas.
I'm using the recommended code from fabric.js
canvas.setOverlayImage('http://fabricjs.com/assets/jail_cell_bars.png', canvas.renderAll.bind(canvas), {
width: width,
height: height,
// Needed to position overlayImage at 0/0
originX: 'left',
originY: 'top'
});
My Fiddle has a fair bit of code, as I'm not sure if it's the resizer or touch events that might be causing this issue.

The problem in your fiddle stems from the fact that in Fabric.js, setting width and height don't scale an image to the given values but rather set the dimensions of the fabric.Image container. What you need to do is call canvas.overlayImage.scaleToWidth(width) (or .scaleToHeight(height)) in the setOverlayImage()'s callback, so that the image would actually be scaled to cover the whole canvas:
//Image Edit
var canvas = new fabric.Canvas('c', {
preserveObjectStacking: true
});
canvas.setWidth(window.innerWidth);
canvas.setHeight(window.innerWidth);
fabric.Image.fromURL("https://4.img-dpreview.com/files/p/E~TS590x0~articles/3925134721/0266554465.jpeg", function(img) {
img.scale(0.5).set({
left: 150,
top: 150,
angle: 0
});
canvas.add(img).setActiveObject(img);
});
var info = document.getElementById('info');
function resize() {
var canvasSizer = document.getElementById("imageEditor");
var canvasScaleFactor = canvasSizer.offsetWidth / 525;
var width = canvasSizer.offsetWidth;
var height = canvasSizer.offsetHeight;
var ratio = canvas.getWidth() / canvas.getHeight();
if ((width / height) > ratio) {
width = height * ratio;
} else {
height = width / ratio;
}
var scale = width / canvas.getWidth();
var zoom = canvas.getZoom();
zoom *= scale;
canvas.setDimensions({
width: width,
height: height
});
canvas.setViewportTransform([zoom, 0, 0, zoom, 0, 0])
canvas.setOverlayImage('https://i.imgur.com/1CURvP5.png', function() {
canvas.overlayImage && canvas.overlayImage.scaleToWidth(width)
canvas.renderAll()
}, {
// Needed to position overlayImage at 0/0
originX: 'left',
originY: 'top'
});
}
window.addEventListener('load', resize, false);
window.addEventListener('resize', resize, false);
var textObj = new fabric.IText("Test Text", {
fontSize: 22,
top: 362.5,
left: 262.5,
hasControls: true,
fontWeight: 'bold',
fontFamily: 'Montserrat',
fontStyle: 'normal',
centeredrotation: true,
originX: 'center',
originY: 'center'
});
canvas.add(textObj);
canvas.renderAll();
canvas.on({
'touch:gesture': function() {
var text = document.createTextNode(' Gesture ');
info.insertBefore(text, info.firstChild);
},
'touch:drag': function() {
var text = document.createTextNode(' Dragging ');
info.insertBefore(text, info.firstChild);
},
'touch:orientation': function() {
var text = document.createTextNode(' Orientation ');
info.insertBefore(text, info.firstChild);
},
'touch:shake': function() {
var text = document.createTextNode(' Shaking ');
info.insertBefore(text, info.firstChild);
},
'touch:longpress': function() {
var text = document.createTextNode(' Longpress ');
info.insertBefore(text, info.firstChild);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.4/fabric.js"></script>
<div id="imageEditor">
<div class="canvas-container">
<canvas id="c"></canvas>
</div>
</div>
(I had to re-upload the jail_cell_bars.png image elsewhere because the original hosting was not cooperating)

Related

Basic Fabric.js Image Selection with Mask

I have a unique (but hopefully simple) issue to fix with Fabric.js to fix.
I have this very simple example below:
I have
2 Images
Both have an absolutePositioned mask via clipPath property on the fabric.Image instance
My issue is:
I want the image to only be selectable (and hoverable) whenever the selection happens within the bounds of the mask, not anywhere on image (even outside of the bounds of its mask).
This image shows the mouse hovering over the red door picture (even though the mouse is outside of the mask bounds, but not outside the image bounds:
Here's a code snippet of the door image snippet:
fabric.Image.fromURL(url1, function(img){
canvas.add(img.set({
left: 0,
top: 0,
clipPath: rect1,
hasControls: false,
}));
img.on('mouseover', () => {
const filter = new fabric.Image.filters.BlendColor({
color: 'white',
alpha: 0.7,
mode: 'tint'
})
img.filters.push(filter)
img.applyFilters()
canvas.renderAll()
})
img.on('mouseout', () => {
img.filters.pop()
img.applyFilters()
canvas.renderAll()
})
}, {crossOrigin: "Anonymous"});
JS Fiddle Example showing the current behavior that I'm trying to change.
A possible solution is to listen to the mouse event in the canvas and toggle the activeObject based on the mouse position:
canvas.observe('mouse:move', function(options) {
const pos = canvas.getPointer(options.e);
if (!imageRight || !imageLeft) return
if (pos.x > 200) {
activeImage = imageRight
} else {
activeImage = imageLeft
}
const activeObj = canvas.getActiveObject();
if (activeImage !== activeObj) {
canvas.setActiveObject(activeImage);
canvas.renderAll()
}
});
This is a very simplified way to detect if the mouse is over the image. It checks if the x > 200 since that is where the line between both images is positioned. This could be improved to be more accurate, but it works just to illustrate the idea.
var canvas = window._canvas = new fabric.Canvas('c');
const url1 = 'https://picsum.photos/300/200'
const url2 = 'https://picsum.photos/320'
let imageRight
let imageLeft
let activeImage
canvas.observe('mouse:move', function(options) {
const pos = canvas.getPointer(options.e);
if (!imageRight || !imageLeft) return
if (pos.x > 200) {
activeImage = imageRight
} else {
activeImage = imageLeft
}
const activeObj = canvas.getActiveObject();
if (activeImage !== activeObj) {
canvas.setActiveObject(activeImage);
canvas.renderAll()
}
});
const baseProps = {
width: 200,
height: 200,
top: 0,
fill: '#000',
absolutePositioned: true,
hasControls: false,
evented: false,
selectable: false
}
const rect1 = new fabric.Rect({
...baseProps,
left: 0,
})
const rect2 = new fabric.Rect({
...baseProps,
left: 200,
})
canvas.add(rect1)
canvas.add(rect2)
fabric.Image.fromURL(url2, function(img) {
imageRight = img
canvas.add(img.set({
left: 200,
top: 0,
clipPath: rect2,
hasControls: false
}))
}, {
crossOrigin: "Anonymouse"
})
fabric.Image.fromURL(url1, function(img) {
imageLeft = img
canvas.add(img.set({
left: 0,
top: 0,
clipPath: rect1,
hasControls: false,
}));
}, {
crossOrigin: "Anonymous"
});
canvas {
border: 2px red solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.6.0/fabric.min.js"></script>
<canvas id="c" width="420" height="220"></canvas>

bringForward in Fabric js

https://jsfiddle.net/techticchetan/p638quv8/3/
I want to select rect object when clicking on Cup image.
Please check below link. I want to do something like this.
http://preview.codecanyon.net/item/fancy-product-designer-woocommercewordpress/full_screen_preview/6318393?_ga=1.254133448.1940140524.1450868289
Thanks,
var canvas = new fabric.Canvas('cv' ) ;
var rect;
fabric.Image.fromURL('http://tmgraphics.biz/test/HTML5_CANVAS%20_TESTING/test-7-21-15/test33/77000_Lime.png', function(img) {
var hRatio = canvas.width / img.width ;
var vRatio = canvas.height / img.height ;
var ratio = Math.min ( hRatio, vRatio );
var centerShift_x = ( canvas.width - img.width*ratio ) / 2;
var centerShift_y = ( canvas.height - img.height*ratio ) / 2;
widdy = img.width*ratio;
hiddy = img.height*ratio;
img.set({
lockMovementX: true,
lockMovementY: true,
hasControls: false,
left: centerShift_x,
top: centerShift_y,
width: widdy,
height: hiddy,
selectable:false
});
canvas.add(img) ;
if (rect) img.bringToFront();
});
rect = new fabric.Rect({
top : 5,
left : 170,
width : 200,
height : 300,
stroke: 'blue', strokeWidth: 2,
fill : ''
});
canvas.add(rect);
canvas.bringToFront(img)
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<canvas id="cv" width="400" height="400" style="border:1px solid black;"></canvas>
I have got answer. Please check this https://github.com/kangax/fabric.js/issues/3506 link
That's quite straightforward, just add an event handler to the image object after you've added it to the canvas:
...
canvas.add(img) ;
if (rect) img.bringToFront();
// Add event handler
img.on('mouseup', function() {
canvas.setActiveObject(rect);
});
If you also want to move it to the front then:
rect.bringToFront();
canvas.renderAll();
I suggest you read the documentation on the Fabric event system in the tutorial

How to free draw circle using Fabric.js?

I am using FabricJS to draw circle in canvas:
var circle = new fabric.Circle({radius: 100,
fill: '',
stroke: 'red',
strokeWidth: 3,
originX: 'center',
originY: 'center'
});
var text = new fabric.Text('HELLO WORLD.',
{ fontSize: 30,
originX: 'center',
originY: 'center',
fill : 'red'
});
var group = new fabric.Group([ circle, text ], {
left: 150, top: 100
});
canvas.add(group);
This code draws a normal circle but I need to freely draw circle with mouse.
Any code help will be appreciated.
According to your previous code for drawing rectangle http://jsfiddle.net/Subhasish2015/8u1cqasa/2/ Here is the code for drawing circle:
$(document).ready(function(){
//Getting the canvas
var canvas1 = new fabric.Canvas("canvas2");
var freeDrawing = true;
var divPos = {};
var offset = $("#canvas2").offset();
$(document).mousemove(function(e){
divPos = {
left: e.pageX - offset.left,
top: e.pageY - offset.top
};
});
$('#2').click(function(){
//Declaring the variables
var isMouseDown=false;
var refCircle;
//Setting the mouse events
canvas1.on('mouse:down',function(event){
isMouseDown=true;
if(freeDrawing) {
var circle=new fabric.Circle({
left:divPos.left,
top:divPos.top,
radius:0,
stroke:'red',
strokeWidth:3,
fill:''
});
canvas1.add(circle);
refCircle=circle; //**Reference of rectangle object
}
});
canvas1.on('mouse:move', function(event){
if(!isMouseDown)
{
return;
}
//Getting yhe mouse Co-ordinates
if(freeDrawing) {
var posX=divPos.left;
var posY=divPos.top;
refCircle.set('radius',Math.abs((posX-refCircle.get('left'))));
canvas1.renderAll();
}
});
canvas1.on('mouse:up',function(){
canvas1.add(refCircle);
//alert("mouse up!");
isMouseDown=false;
//freeDrawing=false; // **Disables line drawing
});
});
});
var Circle = (function() {
function Circle(canvas) {
this.canvas = canvas;
this.className = 'Circle';
this.isDrawing = false;
this.bindEvents();
}
Circle.prototype.bindEvents = function() {
var inst = this;
inst.canvas.on('mouse:down', function(o) {
inst.onMouseDown(o);
});
inst.canvas.on('mouse:move', function(o) {
inst.onMouseMove(o);
});
inst.canvas.on('mouse:up', function(o) {
inst.onMouseUp(o);
});
inst.canvas.on('object:moving', function(o) {
inst.disable();
})
}
Circle.prototype.onMouseUp = function(o) {
var inst = this;
inst.disable();
};
Circle.prototype.onMouseMove = function(o) {
var inst = this;
if (!inst.isEnable()) {
return;
}
var pointer = inst.canvas.getPointer(o.e);
var activeObj = inst.canvas.getActiveObject();
activeObj.stroke = 'red',
activeObj.strokeWidth = 5;
activeObj.fill = 'red';
if (origX > pointer.x) {
activeObj.set({
left: Math.abs(pointer.x)
});
}
if (origY > pointer.y) {
activeObj.set({
top: Math.abs(pointer.y)
});
}
activeObj.set({
rx: Math.abs(origX - pointer.x) / 2
});
activeObj.set({
ry: Math.abs(origY - pointer.y) / 2
});
activeObj.setCoords();
inst.canvas.renderAll();
};
Circle.prototype.onMouseDown = function(o) {
var inst = this;
inst.enable();
var pointer = inst.canvas.getPointer(o.e);
origX = pointer.x;
origY = pointer.y;
var ellipse = new fabric.Ellipse({
top: origY,
left: origX,
rx: 0,
ry: 0,
transparentCorners: false,
hasBorders: false,
hasControls: false
});
inst.canvas.add(ellipse).setActiveObject(ellipse);
};
Circle.prototype.isEnable = function() {
return this.isDrawing;
}
Circle.prototype.enable = function() {
this.isDrawing = true;
}
Circle.prototype.disable = function() {
this.isDrawing = false;
}
return Circle;
}());
var canvas = new fabric.Canvas('canvas');
var circle = new Circle(canvas);
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.17/fabric.min.js"></script>
Please draw circle here
<div id="canvasContainer">
<canvas id="canvas" width="400" height="400" style="border: solid 1px"></canvas>
</div>
Here is the detail blog with jsfiddle - https://blog.thirdrocktechkno.com/sketching-circle-of-a-html5-canvas-using-the-fabricjs-f7dbfa20cf2d
Here is an example of drawing a rectangle which I carefully made and works for latest versions. Krunan example seems to work OK- just in case this is a rectangle free drawing implementation that doesn't use DOM apis like e.clientX, offsetLeft, etc to track the coords, but fabric.js APIs only which I think is safer. Also unregister event listeners - I'm still trying to refine it since I need free drawing support for my project - Since there is no official support for this I wanted to reference the example here for others.
https://cancerberosgx.github.io/demos/misc/fabricRectangleFreeDrawing.html
An easy way to add a Circle to a canvas:
canvas.add(new fabric.Circle({ radius: 30, fill: "green", top: 100, left: 100 }));

Resizing Objects in Fabric.js

I'm planning on using Frabic.js to build a room layout. It's based around a grid layout (grid size: 25) with the objects snapping into position.
I'm trying to override resize events to make the width a multiple of the grid size (25). However it seems to be randomly resizing the the element.
Code
var canvas = new fabric.Canvas('section', { selection: true }); fabric.Object.prototype.transparentCorners = false;
var canvasWidth = 600;
var canvasGrid = 25;
canvas.on('object:modified', function(options) {
options.target.set({opacity: 1}); // Return the opacity back to 1 after moving
var newWidth = (Math.round(options.target.getWidth() / canvasGrid)) * canvasGrid;
console.log("Width:" + options.target.getWidth());
console.log("Desired width: " + newWidth);
if(options.target.getWidth() !== newWidth) {
console.log("alter the width");
options.target.set({ width: newWidth });
console.log("Width changed to: " + options.target.getWidth());
}
console.log("Final width: " + options.target.getWidth());
});
The objects are added on the fly by the end user, the code for it is below.
$("#addBlock").click(function(e){
e.preventDefault();
var block = new fabric.Rect({
left: canvasGrid,
top: canvasGrid,
width: canvasGrid,
height: canvasGrid,
fill: 'rgb(127, 140, 141)',
originX: 'left',
originY: 'top',
centeredRotation: false,
lockScalingX: false,
lockScalingY: false,
lockRotation: false,
hasControls: true,
cornerSize: 8,
hasBorders: false,
padding: 0
});
canvas.add(block);
});
Console Output
Width:170
Desired width: 175
alter the width
Width changed to: 238.00000000000003
Final width: 238.00000000000003
The desired width is what I would like the shapes/blocks to be resized to rather than it's final width.
Probably you can solve resetting the scale factor of your modified object:
options.target.set({ width: newWidth, height: newHeight, scaleX: 1, scaleY: 1, });
try yourself in the snippet below if can fit for your needs:
$(function () {
var canvas = new fabric.Canvas('canvas', { selection: true }); fabric.Object.prototype.transparentCorners = false;
var canvasWidth = 600;
var canvasGrid = 50;
canvas.on('object:modified', function (options) {
options.target.set({ opacity: 1 });
var newWidth = (Math.round(options.target.getWidth() / canvasGrid)) * canvasGrid;
var newHeight = (Math.round(options.target.getHeight() / canvasGrid)) * canvasGrid;
if (options.target.getWidth() !== newWidth) {
options.target.set({ width: newWidth, height: newHeight, scaleX: 1, scaleY: 1, });
}
});
$("#addBlock").click(function (e) {
e.preventDefault();
var block = new fabric.Rect({
left: canvasGrid,
top: canvasGrid,
width: canvasGrid,
height: canvasGrid,
fill: 'rgb(127, 140, 141)',
originX: 'left',
originY: 'top',
centeredRotation: false,
lockScalingX: false,
lockScalingY: false,
lockRotation: false,
hasControls: true,
cornerSize: 8,
hasBorders: false,
padding: 0
});
canvas.add(block);
});
});
canvas {
border: 1px dashed #333;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width="500" height="500"></canvas>
<input type="button" id="addBlock" value="add" />

Drag And Drop Image to Canvas (FabricJS)

The Problem
I want to do this with an image instead of a canvas object. Meaning you have to add the thing you want to add TO AND AS A PART of the canvas before you can add it. The images are actually part of the website so it doesn't need to do some intricate stuff. This code I found here only works for when it's an object not an actual element. And by the way I'm using FabricJS just to let you know that I'm not using the default HTML5 canvas stuff.
As for any alternatives that are possibly going to work without using my current code. Please do post it down below in the comments or in the answers. I would really love to see what you guys got in mind.
Summary
Basically I want to be able to drag and drop images through the canvas while retaining the mouse cursor position. For example if I drag and image and the cursor was at x: 50 y: 75 it would drop the image to that exact spot. Just like what the code I found does. But like the problem stated the CODE uses an object for you to drag it to the canvas then it clones it. I want this functionality using just plain old elements. E.g: <img>.
THE CODE -
JsFiddle
window.canvas = new fabric.Canvas('fabriccanvas');
var edgedetection = 8; //pixels to snap
canvas.selection = false;
window.addEventListener('resize', resizeCanvas, false);
function resizeCanvas() {
canvas.setHeight(window.innerHeight);
canvas.setWidth(window.innerWidth);
canvas.renderAll();
}
// resize on init
resizeCanvas();
//Initialize Everything
init();
function init(top, left, width, height, fill) {
var bg = new fabric.Rect({
left: 0,
top: 0,
fill: "#eee",
width: window.innerWidth,
height: 75,
lockRotation: true,
maxHeight: document.getElementById("fabriccanvas").height,
maxWidth: document.getElementById("fabriccanvas").width,
selectable: false,
});
var squareBtn = new fabric.Rect({
top: 10,
left: 18,
width: 40,
height: 40,
fill: '#af3',
lockRotation: true,
originX: 'left',
originY: 'top',
cornerSize: 15,
hasRotatingPoint: false,
perPixelTargetFind: true,
});
var circleBtn = new fabric.Circle({
radius: 20,
fill: '#f55',
top: 10,
left: 105,
});
var triangleBtn = new fabric.Triangle({
width: 40,
height: 35,
fill: 'blue',
top: 15,
left: 190,
});
var sqrText = new fabric.IText("Add Square", {
fontFamily: 'Indie Flower',
fontSize: 14,
fontWeight: 'bold',
left: 6,
top: 50,
selectable: false,
});
var cirText = new fabric.IText("Add Circle", {
fontFamily: 'Indie Flower',
fontSize: 14,
fontWeight: 'bold',
left: 95,
top: 50,
selectable: false,
});
var triText = new fabric.IText("Add Triangle", {
fontFamily: 'Indie Flower',
fontSize: 14,
fontWeight: 'bold',
left: 175,
top: 50,
selectable: false,
});
var shadow = {
color: 'rgba(0,0,0,0.6)',
blur: 3,
offsetX: 0,
offsetY: 2,
opacity: 0.6,
fillShadow: true,
strokeShadow: true
};
window.canvas.add(bg);
bg.setShadow(shadow);
window.canvas.add(squareBtn);
window.canvas.add(circleBtn);
window.canvas.add(triangleBtn);
window.canvas.add(sqrText);
window.canvas.add(cirText);
window.canvas.add(triText);
canvas.forEachObject(function (e) {
e.hasControls = e.hasBorders = false; //remove borders/controls
});
function draggable(object) {
object.on('mousedown', function() {
var temp = this.clone();
temp.set({
hasControls: false,
hasBorders: false,
});
canvas.add(temp);
draggable(temp);
});
object.on('mouseup', function() {
// Remove an event handler
this.off('mousedown');
// Comment this will let the clone object able to be removed by drag it to menu bar
// this.off('mouseup');
// Remove the object if its position is in menu bar
if(this.top<=75) {
canvas.remove(this);
}
});
}
draggable(squareBtn);
draggable(circleBtn);
draggable(triangleBtn);
this.canvas.on('object:moving', function (e) {
var obj = e.target;
obj.setCoords(); //Sets corner position coordinates based on current angle, width and height
canvas.forEachObject(function (targ) {
activeObject = canvas.getActiveObject();
if (targ === activeObject) return;
if (Math.abs(activeObject.oCoords.tr.x - targ.oCoords.tl.x) < edgedetection) {
activeObject.left = targ.left - activeObject.currentWidth;
}
if (Math.abs(activeObject.oCoords.tl.x - targ.oCoords.tr.x) < edgedetection) {
activeObject.left = targ.left + targ.currentWidth;
}
if (Math.abs(activeObject.oCoords.br.y - targ.oCoords.tr.y) < edgedetection) {
activeObject.top = targ.top - activeObject.currentHeight;
}
if (Math.abs(targ.oCoords.br.y - activeObject.oCoords.tr.y) < edgedetection) {
activeObject.top = targ.top + targ.currentHeight;
}
if (activeObject.intersectsWithObject(targ) && targ.intersectsWithObject(activeObject)) {
} else {
targ.strokeWidth = 0;
targ.stroke = false;
}
if (!activeObject.intersectsWithObject(targ)) {
activeObject.strokeWidth = 0;
activeObject.stroke = false;
activeObject === targ
}
});
});
}
More codes that I found but doesn't answer my problem:
var canvas = new fabric.Canvas('c');
canvas.on("after:render", function(){canvas.calcOffset();});
var started = false;
var x = 0;
var y = 0;
var width = 0;
var height = 0;
canvas.on('mouse:down', function(options) {
//console.log(options.e.clientX, options.e.clientY);
x = options.e.clientX;
y = options.e.clientY;
canvas.on('mouse:up', function(options) {
width = options.e.clientX - x;
height = options.e.clientY - y;
var square = new fabric.Rect({
width: width,
height: height,
left: x + width/2 - canvas._offset.left,
top: y + height/2 - canvas._offset.top,
fill: 'red',
opacity: .2
});
canvas.add(square);
canvas.off('mouse:up');
$('#list').append('<p>Test</p>');
});
});
This code adds a rectangle to the canvas. But the problem is this doesn't achieve what I want which is basically, as previously stated, that I want to be able to drag an img element and then wherever you drag that image on the canvas it will drop it precisely at that location.
CREDITS
Fabric JS: Copy/paste object on mouse down
fabric.js Offset Solution
it doesn't need to do some intricate stuff.
A logical framework under which to implement image dragging might be to monitor mouse events using event listeners.
On mouse down over an Image element within the page but not over the canvas, record which image element and the mouse position within the image. On mouse up anywhere set this record back to null.
On mouse over of the canvas with a non empty image record, create a Fabric image element from the Image element (as per documentation), calculate where it goes from the recorded image position and current mouse position, paste it under the mouse, make it draggable and simulate the effect of a mouse click to continue dragging it.
I have taken this question to be about the design and feasibility stages of program development.

Categories