FabricJS - ZoomToPoint not working with backgroundImage - javascript

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/.

Related

Drag object programmatically

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!

Scaling image from the center (fabricjs)

I'm trying to scale an image using the centeredScaling: true option when setting up the Image instance. I have Circle object that is a "on" a slider that is supposed to be the scale.
Here's the example: http://jsfiddle.net/hellatan/tk1qs8ty/
A couple things:
1. it doesn't scale from the center
2. the starting point of the Circle object doesn't correlate correctly scaling the image properly (i'm guessing i'll have to adjust some math for this one, though)
Anyone have any clues as to what I'm doing wrong (mainly #1, #2 would be a bonus to know too).
Don't mind the sloppiness of the code =)
Try setting the origin for x and y to center, and adjust the initial x and y of the image
imgInstance.set({
scaleY: imgH / origH,
scaleX: imgW / origW,
originX: "center",
originY: "center"
});
There's a hack I've seen around, basically it translates points to and from center in a wrapper for scaling/rotating.
Fiddle: http://jsfiddle.net/ywu45fpd/
Functions to translate points
fabric.Object.prototype.setOriginToCenter = function () {
this._originalOriginX = this.originX;
this._originalOriginY = this.originY;
var center = this.getCenterPoint();
this.set({
originX: 'center',
originY: 'center',
left: center.x,
top: center.y
});
};
fabric.Object.prototype.setCenterToOrigin = function () {
var originPoint = this.translateToOriginPoint(
this.getCenterPoint(),
this._originalOriginX,
this._originalOriginY);
this.set({
originX: this._originalOriginX,
originY: this._originalOriginY,
left: originPoint.x,
top: originPoint.y
});
};
New method on canvas:
fabric.util.object.extend(fabric.Canvas.prototype, {
_scale: function(e, target, value) {
var scale = value,
needsOriginRestore = false;
if ((target.originX !== 'center' || target.originY !== 'center') && target.centeredRotation) {
target.setOriginToCenter(target);
needsOriginRestore = true;
}
target.animate({ scaleX: scale, scaleY: scale }, {
onChange: canvas.renderAll.bind(canvas),
easing: fabric.util.ease.easeOutQuad,
onComplete: function() {
if (needsOriginRestore) {
target.setCenterToOrigin(target);
}
target.setCoords();
},
})
canvas.renderAll();
},
});
See mouse:up on fiddle for usage (basically canvas._scale(e, target, 2))
The same wrapper can be applied for rotating.
First step we are adding scale after calling the center of image.
And then scale will be of center:
imgInstance.scale(my_value).center().setCoords()

Having trouble getting the modified rotational angle of fabic.js object retaliative to is original angle

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/

get color of a pixel

I want to get color of a x y pixel with javascript/jquery, so googled and found that it could be done with canvas.
var canvas = $("<canvas>"); //Create the canvas element
//Create a layer which overlaps the whole window
canvas.css({ position: "fixed", top: "0", left: "0",
width: "100%", height: "100%", "z-index": 9001
});
//Add an event listener to the canvas element
canvas.click(function (ev) {
var x = ev.pageX, y = ev.pageY;
var canvas = this.getContext("2d");
canvas.drawWindow(window, x, y, 1, 1, "transparent");
var data = canvas.getImageData(0, 0, 1, 1).data;
var hex = rgb2hex(data[0], data[1], data[2]);
alert(hex);
$(this).remove();
});
but its not working (drawWindow in firefox not working, not working in chrome too).
any ideas ?
drawWindow is a custom JavaScript implementation. You have to include it before you can use it.
If you are referring to the native method drawWindow(), it cannot be used in a web content that's why it won't work.

Interactive drawing with Fabric.js

I am trying to do an interactive drawing using Fabric.js. Now I can draw a rectangle by using mouse. But after I finish drawing the rectangle, I can not select it unless I resize it once by using the left top controller after drawing. I wonder what break the event system.
Here is my code: http://jsfiddle.net/rmFgX/1/
var canvas = new fabric.Canvas('canvas');
var rect = new fabric.Rect({
top : 100,
left : 100,
width : 60,
height : 70,
fill : 'red'
});
canvas.add(rect);
canvas.on('mouse:down', function (option) {
console.log(option);
if (typeof option.target != "undefined") {
return;
} else {
var startY = option.e.offsetY,
startX = option.e.offsetX;
console.log(startX, startY);
var rect2 = new fabric.Rect({
top : startY,
left : startX,
width : 0,
height : 0,
fill : 'transparent',
stroke: 'red',
strokewidth: 4
});
canvas.add(rect2);
console.log("added");
canvas.on('mouse:move', function (option) {
var e = option.e;
rect2.set('width', e.offsetX - startX);
rect2.set('height', e.offsetY - startY);
rect2.saveState();
});
}
});
canvas.on('mouse:up', function () {
canvas.off('mouse:move');
});
updated the fiddle http://jsfiddle.net/rmFgX/5/
For an object when changing position/dimension -related properties (left, top, scale, angle, etc.) set does not update position of object's borders/controls.
If you need to update those, call:
setCoords().

Categories