fabric.js: Does resizing image using Image.set() reduce image quality? - javascript

I need to reduce the height/width of an image before adding to a Canvas. We are using fabric.js.
When the image is resized using the image.set() function shown below, does it degrade the image quality?
imgAdd.onload = function () {
var img = new fabric.Image(imgAdd);
var imgSizeObj = img.getOriginalSize();
var newImgSize = calculateAspectRatioFit(imgSizeObj.width, imgSizeObj.height, canvas.width, canvas.height);
if (imgSizeObj.width > canvas.width || imgSizeObj.height > canvas.height) {
//Does img.set() preserve image resolution?
img.set({
width: newImgSize.width,
height: newImgSize.height
});
}
canvas.add(img);
}
The goal is to maintain image quality but automatically scale a large image to fit within the canvas.
Thank you,

No it doesnt.
The image is stored in a property of the object._element and does not change unless you apply some filter over it.
Even in that situation a copy is stored in object._originalElement.

Please try the following:
var scale = bef;
img.set({
scaleX: scale,
scaleY: scale
});
You can find more information on this here: https://github.com/kangax/fabric.js/issues/176

Related

Set background image for Fabric Canvas dynamically

I want to add draw shapes on a Image, so decided to use Fabric JS. I am able to get all shapes and objects working well. Now How do I background set exactly to Image. The Image is dynamic, I want to draw on top of that image, and basically store the annotations of objects for backend processing.
Existing solution using Canvas
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
canvas.width = 903;
canvas.height = 657;
var background = new Image();
background.src = "http://www.samskirrow.com/background.png";
// Make sure the image is loaded first otherwise nothing will draw.
background.onload = function(){
ctx.drawImage(background,0,0);
}
Reference - https://stackoverflow.com/a/14013068/2094670
I like this solution.
Live Demo
My Current Fabric JS Code
// Initialize a simple canvas
var canvas = new fabric.Canvas("c", {
hoverCursor: 'pointer',
selection: true,
selectionBorderColor: 'green',
backgroundColor: null
});
// Define the URL where your background image is located
var imageUrl = "../dog.jpg";
// Define
canvas.setBackgroundImage(imageUrl, canvas.renderAll.bind(canvas), {
// Optionally add an opacity lvl to the image
backgroundImageOpacity: 0.5,
// should the image be resized to fit the container?
backgroundImageStretch: false
});
Html
<canvas id="c"></canvas>
Problem.
The image of dog is full hd image, however I see only portion of it. How to do render the background image to its actual height and width using Fabric Canvas ? Since Images are comming dynamically, I might not know exact height and width to hardcode it.
Here's the way to set canvas size base on image size via fabric.js.
It's done initiating the Fabric canvas inside the onload callback, that way we are able to get the image width and height, then set them into the setDimesions method.
img.onload = function () {
...
canvas.setDimensions({ width: img.width, height: img.height });
};
var imageUrl = "http://i.imgur.com/yf6d9SX.jpg";
var background = new Image();
background.src = imageUrl;
// wait for the image to load, then set Fabric Canvas on the callback that runs after image finishes loading
background.onload = function () {
var canvas = new fabric.Canvas("c", {
hoverCursor: "pointer",
selection: true,
selectionBorderColor: "green",
backgroundColor: null,
});
// set canvas width and height based on image size
canvas.setDimensions({ width: background.width, height: background.height });
canvas.setBackgroundImage(imageUrl, canvas.renderAll.bind(canvas), {
// Optionally add an opacity lvl to the image
backgroundImageOpacity: 0.5,
// should the image be resized to fit the container?
backgroundImageStretch: false,
});
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.1.0/fabric.min.js"></script>
<canvas id="c"></canvas>

Pixel manipulation with FabricJS

I'm using FabricJS v1.5.0 and have a problem when manipulated pixel by pixel on the canvas.
this.canvas = new this.fabric.Canvas('canvas');
let imageData = this.canvas.contextContainer.getImageData(0, 0, this.canvas.getWidth(), this.canvas.getHeight());
//here a changed imageData
this.canvas.contextContainer.putImageData(imageData, 0, 0);
//data seted in canvas.
let imageAdd = new this.fabric.Image(image, {
left: 100,
top: 100,
width: 100,
height: 100
});
this.canvas.add(imageAdd).setActiveObject(imageAdd);
//in this moment, the canvas don't have more the imageData setted
Why add image clear imageData? I need to transform imageData in FabricJS Object to add in canvas?
Yes, I think you do need to turn your image data into a fabricjs image. When you need to save the state of the canvas you can do this:
var dataUrl;
....
// Save canvas state
dataUrl = canvas.toDataURL()
// Make changes to the canvas
Then when you need to restore the canvas from it's saved state:
var img = fabric.Image.fromURL(dataUrl, function (i) {
canvas.clear();
canvas.add(i);
canvas.renderAll();
});
You should then be able to add other images as before.
What you need to find out is if your image is actually an image object, because fabric.Image() needs your image object.
If it's a URL or Blob format of your image ( which I guess it is ), you need to use fabric.Image.fromURL() and provide the src of the image not the whole image object.
Here is an example on how to create an instance of fabric.Image from a URL string
fabric.Image.fromURL(link, function(img) {
img.set({
id : 'someId',
width : canvas.width / 2,
height : canvas.height / 2
});
canvas.add(img).renderAll().setActiveObject(img);
});

fabric js - Resize complete canvas according to a rectangle added in a canvas in order to achieve cropping

I am using fabric js for generating templates, I want user to set height and width of a canvas for which I am using following code
canvas.setHeight(height);
canvas.setWidth(width);
However on doing this, the full width canvas stretches itself and the object disappears from the resized canvas as it was lets say 500 px wide before and user resized it to 100px then the items disappear.
I want to achieve a functionality so that if a user wants to change the size of canvas then instead of resizing the canvas I will show a rectangle and user can move rectangle accordingly to get the visible area and once user clicks on save then I will resize the canvas according to that rectangle, so that I can process the SVG later for further conversions but by doing so I am not sure how to get the visible area in that rectangle to the resized canvas, in short I want functionality like Darkroom js but for fabric js canvas object.
The current functionality is added to this JS fiddle http://jsfiddle.net/tbqrn/102/
Finally after doing some research I am able to do that, instead of resizing the canvas I am adding a rectangle object with "cropper" type as mentioned below
var rect = new fabric.Rect({
left: 100,
top: 100,
fill: 'transparent',
width: 400,
height: 400,
strokeDashArray: [5, 5],
stroke: 'black',
type: 'cropper',
lockScalingX: true,
lockScalingY: true,
lockRotation: true
});
canvas.add(rect);
This rectangle will serve as the cropper, when a user submits the form then I am getting that cropper's dimensions as follow along with changing canvas size
var i;
var croppedLeft = 0;
var croppedTop = 0;
var canvasJson = canvas.getObjects();
// Cropping canvas according to cropper rectangle
if (canvas.getObjects().length > 0) {
var i;
for (i = 0; i < canvas.getObjects().length; i++) {
if (canvas.getObjects()[i].type == 'cropper') {
croppedLeft = canvas.getObjects()[i].left;
croppedTop = canvas.getObjects()[i].top;
canvas.setHeight(canvas.getObjects()[i].height);
canvas.setWidth(canvas.getObjects()[i].width);
canvas.getObjects()[i].remove();
}
}
}
And after that I am shifting all the other canvas objects accordingly as follow.
for (i = 0; i < canvasJson.length; i++) {
canvas.getObjects()[i].left = canvas.getObjects()[i].left - croppedLeft
canvas.getObjects()[i].top = canvas.getObjects()[i].top - croppedTop
canvas.renderAll();
}
And after doing that I am able to achieve the desired functionality, hope this helps someone.
Here is my fiddle http://jsfiddle.net/tbqrn/115/

Is there a way to use JCrop to crop an area larger than the actual image?

From what I can tell, JCrop will not let me set things up so the user can crop outside the actual image and include surrounding whitespace. Is there a way to do that?
To help explain what I mean, say we are restricting our crop to a 16:9 ratio. That works fine for an image with a naturally wide subject:
But sometimes the source image that a user wants to use does not comfortably accommodate the desired ratio:
Instead, we'd like to allow them to include space outside the image by making the crop area larger than the image itself:
I've been messing around with JCrop and looking through the manual and Google for a while and it doesn't look like this is possible (without modifying JCrop). Am I wrong? If so, how do you do it?
FWIW, the actual images in this case will be product/organization logo images, which come in a large variety of aspect ratios, and almost always the images available to people have almost no whitespace around the text/imagery. Which means any fixed aspect ratio crop restricted to the bounds of the image will almost certainly chop off either the top+bottom or left+right sides of the image.
My solution was to create a temporary canvas with square dimensions equal to the largest side of the image. I made the canvas background white and added the image in the center. Then I created a new image and used the canvas as the image source. Then I used that image with jcrop. It's slower, but it works!
Here's an example:
img.onload = function(){
// get the largest side of the image
// and set the x and y coordinates for where the image will go in the canvas
if( img.width > img.height ){
var largestDim = img.width;
var x = 0;
var y = (img.width-img.height)/2;
}
else{
var largestDim = img.height;
var y = 0;
var x = (img.height-img.width)/2;
}
// create a temporary canvas element and set its height and width to largestDim
canvastemp = document.createElement("canvas");
canvastemp.width = canvastemp.height = largestDim;
var ctx = canvastemp.getContext('2d');
// set the canvas background to white
ctx.fillStyle="#FFFFFF";
ctx.fillRect(0, 0, canvastemp.width, canvastemp.height);
// center the image in the canvas
ctx.drawImage(img, x, y, img.width, img.height);
// create a new image and use the canvas as its source
var squaredImg = document.createElement("img");
squaredImg.src = canvastemp.toDataURL();
// add jcrop once the image loads
squaredImg.onload = function(){
addJcrop(squaredImg);
}
};
function addJcrop(img){
// your jcrop code
}
This way users can choose to include the entire image in the crop if they wish.
consider using something like php imagick to convert the photo to photo + transparent big background and then put that to JCrop I dont think its possible other way
You could fool the jCrop script. Instead of showing image.jpg, you do something like not_a_real_image.php?imagename=image.jpg.
Then give the php file a header of the image, and a width and height, and align the actual image in the center of that.
All you have to do is remember the amount of canvas you've added to correct it later on.
I made a function using Imagick:
function resizeImage($imgSrc, $width, $height, $createBg, $output, $show) {
$img = new Imagick($imgSrc);
if ($img->getImageWidth() / $img->getImageHeight() < $width / $height) {
$img->thumbnailImage(0, $height);
} else {
$img->thumbnailImage($width, 0);
}
$canvas = new Imagick();
$canvas->newImage($width, $height, 'white', 'jpg');
/* Creates a background image (good for vertical images in horizontal canvas or vice-versa) */
if ($createBg) {
$imgBg = new Imagick($imgSrc);
if ($imgBg->getImageWidth() / $imgBg->getImageHeight() < $width / $height) {
$imgBg->thumbnailImage($width, 0);
} else {
$imgBg->thumbnailImage(0, $height);
}
$imgBg->blurImage(0, 80);
$geometryBg = $imgBg->getImageGeometry();
$xBg = ( $width - $geometryBg['width'] ) / 2;
$yBg = ( $height - $geometryBg['height'] ) / 2;
$canvas->compositeImage( $imgBg, imagick::COMPOSITE_OVER, $xBg, $yBg );
}
/* Center image */
$geometry = $img->getImageGeometry();
$x = ( $width - $geometry['width'] ) / 2;
$y = ( $height - $geometry['height'] ) / 2;
$canvas->compositeImage( $img, imagick::COMPOSITE_OVER, $x, $y );
/* Save image */
if ($output) {
$canvas->writeImage($output);
}
/* Show the image */
if ($show) {
header( 'Content-Type: image/jpg' );
echo $canvas;
}
}
The comment's explain it all, enjoy!

How can I dynamically set the image size ratio depending on the returned image in raphael?

How can I dynamically set the image size ratio depending on the returned image in raphael?
Here is some code to give you an idea:
var viewer = Raphael(0,0,scrWidth, scrHeight);
viewer.image(dynamicUrl, 140, 140,300, scaledHeight);
Thank you
You can load the image outside the DOM and get its dimensions... You can put this inside a function:
var myImg = new Image();
myImg.src = dynamicUrl;
myImg.onload = function() {
var width = myImg.width;
var height = myImg.height;
var scale = 0.5; // for example
var viewer = Raphael(0,0,width, height); // or whatever other size
viewer.image(dynamicUrl, 0, 0, width*scale, height*scale); // scale image
// after the image is in the viewer you can use .scale()
}
jsFiddle
Now you can divide or multiply both width and height to scale. Make sure you pay attention to the timing.
Also, once the image is in Raphael, you can use .scale()

Categories

Resources