Fabricjs resize loses resolution - resolution

I have a website and there is one part of it where the person can upload an image and resize this image. To change the size of the image is used the Fabricjs (http://fabricjs.com/).
The problem is when the image is resized it loses resolution, it appears very ugly after changing size. Here is the code used to accomplish that:
function addImage(imgSrc, img_name, colorArr)
{
console.log("add image call")
var splitArr = colorArr.split(",");
show_image();
jQuery("#img_name").html(img_name);
fabric.Image.fromURL(imgSrc, function (img) {
var theScaleFactor=getScaleFactor(img.width,img.height,parseInt(jQuery(".canvas-container").css("width")),parseInt(jQuery(".canvas-container").css("height")));
img.set({
left : 0,
top : 0,
id:'redux',
orig_name:img_name,
imgColor:colorArr
}).scale(theScaleFactor.scale).setCoords(); //HERE THE IMAGE IS DECREASED/RESIZED
canvas.add(img);
//console.log("wt = "+img.get('width')+" ht = "+img.get('height')+" scale = "+theScaleFactor.scale)
img.set({left:((canvas.getWidth()/2) - (parseInt(img.get('width'))*theScaleFactor.scale)/2), top:(45-(parseInt(img.get('height')*theScaleFactor.scale)/2))});
canvas.setActiveObject(img);
canvas.renderAll();
countColors();
});
jQuery("#dropbox").hide();
jQuery(".preloader").hide();
}
I found this link and tried to reduce the image's size gradually, but it didn't work. I tried this way:
img.set({
left : 0,
top : 0,
id:'redux',
orig_name:img_name,
imgColor:colorArr
});
img.scale(0.5);
img.scale(0.5);
img.scale(0.5);
img.scale(0.5);
img.scale(0.5);
img.scale(0.5);
img.scale(0.5);
img.scale(0.5);
img.setCoords();
canvas.add(img);
I found this link too and tried to reduce image's size like below, but it didn't work as well:
img.set({
left : 0,
top : 0,
id:'redux',
orig_name:img_name,
imgColor:colorArr
});
img.filters.push(new fabric.Image.filters.Resize({scaleX: 0.2, scaleY: 0.2}));
img.applyFilters(canvas.renderAll.bind(canvas)).setCoords();
canvas.add(img);
I hope someone can help. I appreciate any help.
===============================
UPDATE with answer:
This way it worked:
fabric.Image.fromURL(imgSrc, function (img) {
var theScaleFactor = getScaleFactor(img.width,img.height,parseInt(jQuery(".canvas-container").css("width")),parseInt(jQuery(".canvas-container").css("height")));
img.set({
left : 0,
top : 0,
id:'redux',
orig_name:img_name,
imgColor:colorArr
});//.scale(theScaleFactor.scale).setCoords();
img.filters.push( new fabric.Image.filters.Resize( { resizeType: 'sliceHack', scaleX: theScaleFactor.scale, scaleY: theScaleFactor.scale } ) );
img.applyFilters();
img.setCoords();
canvas.add(img);
//console.log("wt = "+img.get('width')+" ht = "+img.get('height')+" scale = "+theScaleFactor.scale)
img.set({left:((canvas.getWidth()/2) - (parseInt(img.get('width'))*theScaleFactor.scale)/2), top:(45-(parseInt(img.get('height')*theScaleFactor.scale)/2))});
canvas.setActiveObject(img);
canvas.renderAll();
countColors();
});
jQuery("#dropbox").hide();
jQuery(".preloader").hide();
}

The image does not lose resolution, the ugly effect you notice is from the "nearest neighbour" resize algorithm that the canvas uses.
To solve this, fabricJS implemented a resize filter class that allows you to use 'bilinear', 'hermite', 'lanczos' or this 'sliceHack' you quoted.
The filter can be applied one time at loading or during every manual resize.
regarding your tries, take note that fabricJS does not scale the image when you call image.scale(0.5), but just on rendering.
So calling image.scale() multiple time does not have any effect. The image is scaled by the internal property scaleX and scaleY once at rendering time.

Related

Using OpenSeadragon, how can set it to load the image at a specific set of coordinates in the upper left corner?

I am using OpenSeadragon to display a large image so that it scrolls infinitely as a mosaic. This is working fine, with the code listed below. However, the initial zoom level varies when opened in Chrome, Firefox or Opera, and the image is displayed from a random position within the image, instead of having the desired coordinates in the upper left corner.
Two related questions:
Are there properties to be set to specify the coordinates of the image that should be displayed in the upper left corner when the image is first loaded?
Is there a property to specify the zoom level when the image is first loaded? I set defaultZoomLevel to 0.6 but each browser seem to react differently to it, with Chrome being the only one to get it about right and the other two showing a much more zoomed out image.
Thanks for any help!
<body>
<div id="openseadragon1" style="width: 6560px; height: 3801px;"></div>
<script src="/openseadragon/openseadragon.min.js"></script>
<script type="text/javascript">
var viewer = OpenSeadragon({
id: "openseadragon1",
showNavigationControl: false,
wrapHorizontal: true,
wrapVertical: true,
visibilityRatio: 0,
zoomPerScroll: 1.2,
defaultZoomLevel: 0.6,
minZoomImageRatio: 0.6,
maxZoomPixelRatio: 2.5,
prefixUrl: "/openseadragon/images/",
tileSources: {
type: 'image',
url: '/myBigImage.png'
}
});
// -------------------------------------
// Edit based on iangilman's reply
// -------------------------------------
viewer.addHandler('open', function() {
var tiledImage = viewer.world.getItemAt(0);
var imageRect = new OpenSeadragon.Rect(10, 50, 1000, 1000);
var viewportRect = tiledImage.imageToViewportRectangle(imageRect);
viewer.viewport.fitBounds(viewportRect, true);
});
</script>
</body>
Yes, the zoom levels in OpenSeadragon are relative to the width of the viewport (a zoom of 1 means the image is exactly filling the viewport width-wise), which is probably why you're getting different results on different devices. If you want to choose a specific portion of the image, you'll have to convert from image coordinates to viewport coordinates. Either way, your best bet for reliable results is to explicitly choose the location after the image loads. For example:
viewer.addHandler('open', function() {
// Assuming you are interested in the first image in the viewer (or you only have one image)
var tiledImage = viewer.world.getItemAt(0);
var imageRect = new OpenSeadragon.Rect(0, 0, 1000, 1000); // Or whatever area you want to focus on
var viewportRect = tiledImage.imageToViewportRectangle(imageRect);
viewer.viewport.fitBounds(viewportRect, true);
});

FabricJS 2 - Image isn't stretching to the given width

I have just upgraded from fabric 1.7 to 2 and now the image object is behaving differently.See the screenshot, the image where the arrow is is completely ignoring the fact that i set a width on it, it looks like it's actually scaling it based on the given height to keep the image ratio. I don't want this to happen, the image needs to stretch to the size i tell it to.
Anyone have any idea to stop it doing this? I mean if i set a width in the options for the image object i expect it to respect those dimensions. It should be stretching to fill where the red box is.
This is happening when loading the image initially as a square and setting {width:1000,height:400} for example, but instead it looks like it's taking the height and scaling the width down to keep it square.
You need to set scaleX for width and scaleY for height. It's a breaking change for v2.
DEMO
var canvas = new fabric.Canvas('c');
var index = 0,
json;
var url = '//fabricjs.com/assets/pug.jpg';
fabric.Image.fromURL(url, function(img) {
var elWidth = img.naturalWidth || img.width;
var elHeight = img.naturalHeight || img.height;
img.set({
scaleX:200/elWidth,
scaleY:200/elHeight
})
canvas.add(img);
})
canvas{
border:2px solid #000;
}
<script type="text/javascript" src="
https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id="c" width="400" height="400"></canvas>

how to stretch image size to match fabric.Image object

I am using fabricjs to implement image editing and I try to use a fabric.Image object as the background image of canvas to store the data. And the following is the code:
var canvas = new fabric.Canvas('canvasId');
var imageObject = new fabric.Image($originImage);
canvas.add(imageObject);
but I found the $originImage's size is much larger than canvas' size and also imageObject's size, so the canvas can only show part of the image. I want to know how to stretch the $originImage to adapt the canvas then canvas can display all of the $originImage?
Here what I have done
$canvas.width = $originImage.clientWidth;
$canvas.height = $originImage.clientHeight;
var fabricCanvas = new fabric.Canvas('canvasId');
// canvas.setFabricCanvas(fabricCanvas);
var imageObject = new fabric.Image($originImage);
// fabricCanvas.add(imageObject);
// fabricCanvas.isDrawingMode = true;
fabricCanvas.setBackgroundImage(imageObject, fabricCanvas.renderAll.bind(fabricCanvas), {
scaleX: fabricCanvas.width / $originImage.naturalWidth,
scaleY: fabricCanvas.height / $originImage.naturalHeight
});
the upper is my related code and below is the display:
it is solved, and the previous question is because I resize the $originImage first, so when I input the image src as setBackgroundImage's parameter, it can display normally.
For version 2.0 of fabricjs, they have changed the way to handle width/height compared to previous version. If you apply width/height, then it basically crop the image to that particular size compared to the original image size. In order to resize it to a proper size, you have to switch to use scaleX/scaleY like other people have suggested.
For example, I use image.fromUrl to load an image and set it to be the background:
fabric.Image.fromURL(imgUrl, function(img) {
img.set({
scaleX: currentWidth / img.width,
scaleY: currentHeight / img.height,
top: topPosition,
left: leftPosition
originX: 'left', originY: 'top'
});
canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas));
});
where currentWidth/currentHeight can be your canvas size if you want full background or they can be a specific width/height that you want (in my project, I want to do letter-boxed image instead so I set the width and height based on my letter-boxing algorithm), and top/left is the location that you want to place your image in the canvas (leave it none if you want to be full background image). Do not set any width and height since that will crop the scaled image rather than setting the image to be the exact size.
If this does not work, check the backgroundImage object from the canvas and see if its dimension and scale properties are different compared to a manual calculation. If you take a look, you will see the width and height properties are your natural image width and height, but it will have scaleX and scaleY less than 1 if your canvas size is less than the image size or more than 1 if it is bigger.
Also I see you are loading image directly into an image object. That might be different compared to load the data and set it directly using setBackgroundImage.
canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas), {
scaleX: canvas.width / $originalImg.naturalWidth,
scaleY: canvas.width / $originalImg.naturalHeight
});
use scaleX,scaleY to resize.
(function() {
var $originalImg = $('#originalImage')[0];
console.dir($originalImg)
var canvas = this.__canvas = new fabric.Canvas('c');
var img = new fabric.Image($originalImg);
canvas.setBackgroundImage(img,canvas.renderAll.bind(canvas),{
scaleX:canvas.width/$originalImg.naturalWidth,
scaleY:canvas.width/$originalImg.naturalHeight
});
})();
canvas{
border-width: 1pz;
border-style: solid;
border-color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.0.0-rc.3/fabric.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id='originalImage'src='http://fabricjs.com/assets/pug_small.jpg'>
<canvas id='c' width=200 height=200></canvas>
I am using the following script to ensure the image is no larger than the canvas width:
var aspect = image.width / image.height; //Aspect ratio of image
new fabric.Image(image, {
scaleX: canvas.width / image.width,
scaleY: canvas.width / (image.height * aspect)
});

Applying clipTo path on image in fabric.js incorrectly repositions the image

Please take a look at this fiddle:
http://jsfiddle.net/2ktvyk4e/5/
var imgUrl, snapshotCanvas;
imgUrl = 'http://cdn-development.wecora.com/boards/backgrounds/000/001/388/cover/ocean-background.jpg';
snapshotCanvas = new fabric.StaticCanvas('snapshotCanvas', {
backgroundColor: '#e0e0e0',
width: 1000,
height: 1500
});
fabric.Image.fromURL(imgUrl, function(img) {
img.set({
width: 1000,
left: 0,
top: 0,
clipTo: function(ctx) {
return ctx.rect(0, 0, 1000, 400);
}
});
return snapshotCanvas.add(img).renderAll();
}, {
crossOrigin: 'Anonymous'
});
It's pretty simple. I'm loading an image and then trying to clip it so that the full width of the canvas but clipped so only the top 400 pixels are showing. For some reason, the clipTo causes the image to move and resize inexplicably:
As you can see, when the clipping path is applied the image is repositioned on the canvas inexplicably. If I remove the clipTo, then the image loads full canvas width no problem (of course its also full height, which we don't want).
I have no idea what is happening here or why this is occuring so any help is appreciated.
Make sure you have originX and originY left to top and left on both the canvas and your image. Also - you don't really need to clip anything to the canvas. The only real use I've found for clipTo was clipping collage images to their bounding shapes. If you want to restrict the image from being dragged above that 400px, I would recommend rendering a rectangle below it (evented = false, selectable = false) and then clipping to that rectangle.
I put this together without clipTo (and changed some numbers so I wasn't scrolling sideways). It renders the image half way down the canvas.
http://jsfiddle.net/2ktvyk4e/6/
Edit:
I dug through some source code to find the clipByName method and the two helper methods for finding stuff. I use this for keeping track of collage images and their bounding rectanlges ("images" and "clips"). I store them in an object:
imageObjects: {
'collage_0': http://some.tld/to/image.ext,
'collage_1': http://some.tld/to/image2.ext
}
Helper methods for finding either the clip or image:
findClipByClipName: function (clipName) {
var clip = _(canvas.getObjects()).where({ clipFor: clipName }).first();
return clip;
},
findImageByClipFor: function (clipFor) {
var image = _(canvas.getObjects()).where({ clipName: clipFor }).first();
return image;
},
Actual clipping method:
clipByName: function (ctx) {
this.setCoords();
var clipRect, scaleXTo1, scaleYTo1;
clipRect = collage.findClipByClipName(this.clipName);
scaleXTo1 = (1 / this.scaleX);
scaleYTo1 = (1 / this.scaleY);
ctx.save();
var ctxLeft, ctxTop;
ctxLeft = -(this.width / 2) + clipRect.strokeWidth;
ctxTop = -(this.height / 2) + clipRect.strokeWidth;
ctx.translate(ctxLeft, ctxTop);
ctx.rotate(degToRad(this.angle * -1));
ctx.scale(scaleXTo1, scaleYTo1);
ctx.beginPath();
ctx.rect(
clipRect.left - this.oCoords.tl.x,
clipRect.top - this.oCoords.tl.y,
clipRect.width,
clipRect.height
);
ctx.closePath();
ctx.restore();
function degToRad(degrees) {
return degrees * (Math.PI / 180);
}
},
And finally adding images to canvas where all of this comes together:
var clipName, clip, image;
clipName = helpers.findKeyByValue(url, this.imageObjects);
clip = this.findClipByClipName(clipName);
image = new Image();
image.onload = function () {
var collageImage = new fabric.Image(image, $.extend({}, collage.commonImageProps, {
left: clip.left,
top: clip.top,
clipName: clipName,
clipTo: function (ctx) {
return _.bind(collage.clipByName, collageImage)(ctx);
}
}));
collage.scaleImagesToClip(collageImage);
canvas.add(collageImage);
};

Text always displays under image in Fabric.js

I have the following problem. I have been using Fabric.js for a project and find it easy to use. However I have the following problem that i just don't seem able to solve. I am probably missing the obvious but its time to ask for help.
I can't get a text layar to display ontop of a loaded image. here is the code :
<canvas id="c" height=600 width=800></canvas>
var canvas = new fabric.StaticCanvas('c');
fabric.Image.fromURL('http://mozorg.cdn.mozilla.net/media/img/products/badge- firefoxos.jpg?2013-06', function(img) {
var imgX = img.set({
top: 0,
left: 0,
});
canvas.add(imgX);
});
var text = new fabric.Text("This text always gets burried", {
top : 0,
left : 0,
fontSize : 50,
fontFamily : 'Delicious_500'
});
canvas.add(text);
canvas.BringToFront(text);
canvas.renderAll();
I also created a fiddle : http://jsfiddle.net/NkqWL/9/
Any advice is greatly appreciated.
I have updated your fiddle
Fiddle Link:- Click Here
Send your image to back using canvas.sendToBack(imgX);
fabric.Image.fromURL('http://mozorg.cdn.mozilla.net/media/img/products/badge-firefoxos.jpg?2013-06', function(img) {
var imgX = img.set({
top: 0,
left: 0,
});
canvas.add(imgX);
canvas.sendToBack(imgX);
});

Resources