Display Image in fixed size div - javascript

I've a 100*100 <div> in which I would like to display images of different sizes randomly without stretching them.
Note:The image should appear as origional, just resizing should be done inorder to place it in box

Maybe this style will help you:
div {
position:relative;
}
div img {
max-width:100%;max-height:100%;
}

here's a simple function to calculate your aspect ratio and size the image down. it takes the path to the file and the original width and height of the image. you can provide all that however you see fit. 'myElement' would be the id of your image element.
function loadImage(filename, width, height) {
var aspect = width / height;
var w, h;
if (width > height) {
w = 100;
h = Math.round(100 / aspect);
}
else {
h = 100;
w = Math.round(100 * aspect);
}
var element = document.getElementById('myElement');
element.src = filename;
element.style.width = w + 'px';
element.style.height = h + 'px';
}

Related

How do I scale an SVG based on my website's window size

I'm trying to use a settings icon svg file which will scale depending on then window width. I've tried to do this by creating a function in JavaScript that changes the element's width and height based on the window size but this doesn't work. (Btw i'm testing it with a width of 360 pixels but the svg's size is about 300 pixels).
The HTML:
<img id="settings-icon" class="icon" src="images/icons/settings-icon.svg" onclick="settingsPage();" alt="Settings" />
The JavaScript:
var settings_icon = scaleIcon(dcument.getElementById("settings-icon"));
scaleIcon(settings_icon);
function scaleIcon(icon) {
var w = window.innerWidth;
var h = window.innerHeight;
if (w <= 360) {
icon.width = "44";
icon.height="44";
}
else if (w <= 400) {
icon.width = "48";
icon.height="48";
}
else if (w <= 440) {
icon.width = "52";
icon.height="52";
}
}
I think you spelt 'document' as 'dcument'. Also, try using icon.style.width and icon.style.height. Also, remember to add the units for your measurements. Example: icon.style.width = "44vw";

Calculate image dimensions on screen size before rendering

Is there a way of calculating / estimating what the image size would be depending on the screen resolution before the image has been rendered? I need more logical help rather than code to be honest. What do I need to calculate?
Image size: 800px * 450px
Window size: 424px * 728px
The image works out to be 424px * 239px. I need to calculate this in code so I can adjust positions of other elements following after (absolute / fixed elements).
What I have done so far is;
var ratio1 = (this.retrievedNewsArticle.featuredImage.width / this.retrievedNewsArticle.featuredImage.height);
var ratio2 = ($(window).innerWidth() / this.retrievedNewsArticle.featuredImage.width);
// Ratio 1 = 424
// Ratio 2 = 0.53
So what's next?
It sounds like you already know the image's size, and it sounds like you want the image to be the full width of the window, and just need to know how to determine the height of the image. If so, the target height is the image height times the windows width divided by the image width:
var renderedWidth = imageWidth;
var renderedHeight = imageHeight * (windowWidth / imageWidth);
That maintains the aspect ratio.
That assumes the image is always wider than the screen. Let's remove that assumption.
If you want the image to stretch to fill:
var renderedWidth, renderedHeight;
if (windowWidth >= imageWidth) {
renderedWidth = imageWidth * (windowWidth / imageWidth);
} else {
renderedWidth = imageWidth;
}
renderedHeight = imageHeight * (windowWidth / renderedWidth);
If you don't want the image to stretch to fill:
var renderedWidth, renderedHeight;
if (windowWidth >= imageWidth) {
renderedWidth = imageWidth;
renderedHeight = imageHeight;
} else {
renderedWidth = imageWidth;
renderedHeight = imageHeight * (windowWidth / imageWidth);
}

If I resize my canvas, my createJS text becames blurry

I'm using createJS to drawn inside the canvas. I have my canvas set to occupy the browser window maintaining aspect ratio using the resize() function.
This is the code:
mytext = new createjs.Text("Lorem ipsum dolor sit amet 2","19px Calibri","#073949");
mytext.x = 450
mytext.y = 300;
stage.addChild(mytext);
resize = function() {
var canvas = document.getElementById('canvas');
var canvasRatio = canvas.height / canvas.width;
var windowRatio = window.innerHeight / window.innerWidth;
var width;
var height;
if (windowRatio < canvasRatio) {
height = window.innerHeight - 35;
width = height / canvasRatio;
} else {
width = window.innerWidth;
height = width * canvasRatio;
}
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';
}()
What happens is that the text gets blurry (decrease of quality) when the canvas resizes.
http://i.imgur.com/RQOSajs.png
vs
http://i.imgur.com/Xwhf5c5.png
How can I solve this issue?
Since you are using CreateJS, you can simply resize the canvas, and scale the entire stage to redraw everything at the new size:
// just showing width to simplify the example:
var newWidth = 800;
var scale = newWidth/myCanvas.width;
myCanvas.width = newWidth;
myStage.scaleX = myStage.scaleY = scale;
myStage.update(); // draw at the new size.
#Adam's answer is correct as far as scaling the canvas goes. You do NOT want to scale with CSS, as it will stretch your canvas instead of changing its pixel dimensions. Set the width and height of the canvas using JavaScript instead.
stage.canvas.width = window.innerWidth;
stage.canvas.height = window.innerHeight;
As you stated in your comment, this will only change the canvas size, and not reposition or scale your content. You will have to do this manually. This is fairly simple. Generally, I recommend putting your "resize" listener in the JavaScript in your HTML file, rather than on a frame script.
First, determine the scale, based on the size of the window and the size of your content. You can use the exportRoot.nominalBounds.width and exportRoot.nominalBounds.height which is the bounds of the first frame. If you want to scale something else, use its nominalBounds instead.
Note that nominalBounds is appended to all MovieClips exported from Flash/Animate. If you enable multi-frame bounds, and want to use those, you will have to modify your approach.
The main idea is to use the original, unscaled size of your contents.
var bounds = exportRoot.nominalBounds;
// Uses the larger of the width or height. This will "fill" the viewport.
// Change to Math.min to "fit" instead.
var scale = Math.max(window.innerWidth / bounds.width, window.innerHeight / bounds.height);
exportRoot.scaleX = exportRoot.scaleY = scale;
You can then center it if you want.
exportRoot.x = *window.innerWidth - bounds.width*scale)/2;
exportRoot.y = *window.innerHeight - bounds.height*scale)/2;
Here is a quick sample of a responsive canvas using a simple shape as the scaling contents:
http://jsfiddle.net/lannymcnie/4yy08pax/
Doing this with Flash/Animate CC export has come up a few times, so it is on my list of future EaselJS demos to include on createjs.com, and in the EaselJS GitHub.
I hope this helps.
Take a look at my jsfiddle : https://jsfiddle.net/CanvasCode/ecr7o551/1/
Basically you just store the original canvas size and then use that to work out new positions and sizes
html
<canvas id="canvas" width="400" height="400">
Canvas was unable to start up.
</canvas>
<button onclick="resize()">Click me</button>
javascript
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var originalWidth = canvas.width;
var originalHeight = canvas.height;
render = function()
{
context.fillStyle = "#DDD";
context.fillRect(0,0, originalWidth * (canvas.width / originalWidth), originalHeight * (canvas.height / originalHeight));
context.fillStyle = "#000";
var fontSize = 48 * (canvas.width / originalWidth);
context.font = fontSize+"px serif";
context.fillText("Hello world", 100 * (canvas.width / originalWidth), 200 * (canvas.height / originalHeight));
}
resize = function()
{
canvas.width = 800;
canvas.height = 600;
render();
}
render();
The HTML5 canvas element works with two different sizes
Visual size on screen, controlled via CSS, like you're setting with canvas.style.width/height
Size of pixel buffer for the drawing, controlled via numeric width and height pixel attributes on the canvas element.
The browser will stretch the buffer to fit the size on screen, so if the two values are not 1:1 ratio text will look blurry.
Try adding the following lines to your code
canvas.width = width;
canvas.height = height;
I created a function to resize all the elements on the screen after resizing the canvas. It saves the initial coordinates and scales for the elements with the original width of 900 px and then it changes them according to the current width ratio relative to the original width ratio. The text isn't blurry/bad quality anymore.
resize = function() {
var canvas = document.getElementById('canvas');
var canvasRatio = canvas.height / canvas.width;
var windowRatio = window.innerHeight / window.innerWidth;
var width;
var height;
if (windowRatio < canvasRatio) {
height = window.innerHeight;
width = height / canvasRatio;
} else {
width = window.innerWidth;
height = width * canvasRatio;
}
canvas.width = width;
canvas.height = height;
reziseElements();
};
reziseElements = function()
{
var canvrat = canvas.width / 900;
//Simplified
stage.scaleX = stage.scaleY = canvrat;
//Old Version
/*for (i=0; i<stage.numChildren ;i++)
{
currentChild = stage.getChildAt(i);
if (typeof currentChild.oscaleX == 'undefined')
{
currentChild.oscaleX = currentChild.scaleX;
currentChild.ox = currentChild.x;
currentChild.oy = currentChild.y;
}
}
for (i=0; i<stage.numChildren ;i++)
{
currentChild = stage.getChildAt(i);
currentChild.scaleX = currentChild.scaleY = currentChild.oscaleX * canvrat
currentChild.x = currentChild.ox * canvrat
currentChild.y = currentChild.oy * canvrat
} */
}

resize image by area

I am trying to write a javascript function to resize an image based on a given area (or in my case (somewhat inaccurate) 'average dimension' since that's easier to think in terms of. Rather than feeding in maximum height and width, I want to feed in maximum area so that long or narrow images will appear visually to be roughly the same size.
I'm getting really caught on the math aspect of it, though... just how to logic it, as I haven't done much math of late.
Basically, given an aspect ratio I want to determine the maximum size within an area.
Something like this:
function resizeImgByArea(img, avgDimension){
var w = $(img).width();
var h = $(img).height();
var ratio = w/h;
var area = avgDimension * avgDimension;
var targetHeight //something involving ratio and area
var targetWidth //something involving ratio and area
$(img).width(targetWidth);
$(img).height(targetHeight);
}
Not sure if this is on topic here, but I'm not able to brain it.
Sounds like you want to constrain the thumbnail's pixels to be as close as possible to the average area as all the other thumbnails, right?
So basically, given the h/w of the original image, and a target area A:
h * w = original image's pixel size (let's got with 640x480 = 307,200 pixels)
A = maximum number of pixels allowed (let's go for 100x100 = 10,000 pixels)
307,200 / 10,000 = 30x reduction
original aspect ratio = 640 / 480 = 1.3333 : 1
To calculate the new thumbnail's x/y size:
newX * newY = 10000
newX = newY * 1.333
(newY * 1.333) * newY = 10000
newY^2 * 1.333 = 10000
newY^2 = 10000 / 1.333
newY^2 = 7502
newY = 86.6 -> 87
newX = 87 * 1.333 = 115.97 -> 116
116 x 87 = 10,092 pixels
if we'd rounded down on the thumbnail sizes, we'd get 86x114 = 9,804 pixels
so... to convert your 640x480 image to a standard 10,000-ish pixel size, you need a new image size of 86-87 height and 114-116 width.
Are you looking for something like:
function resizeImgByArea(img, avgDimension) {
var w = $(img).width();
var h = $(img).height();
var maxWidth = avgDimension;
var maxHeight = avgDimension;
var divisor;
var targetWidth = w;
var targetHeight = h;
if (w > maxWidth || h > maxHeight) {
// Set the divisor to whatever will make the new image fit the dimensions given
if((w - maxWidth) > (h - maxHeight)) {
divisor = w / maxWidth;
}
else {
divisor = h / maxHeight;
}
targetWidth = w / divisor;
targetHeight = h / divisor;
}
$(img).width(targetWidth);
$(img).height(targetHeight);
}
It isn't that hard.
maxPix = average^2
maxPix = x * h + x * w
average^2 = x*h + x*w //: x
average^2/x = h+w
inverse and multiply with average^2
x = average^2 / (h+w)
then multiply h and w with x to get the new dimensions
Here is the function I came up with that's simpler than some mentioned and does what I need. It constrains to a set maxWidth, but not height because of the particular requirements I was using.. it would probly be appropriate to throw on a maxHeight as well as well as some cleanup, but it gets 'er done.
function resizeImgByArea(imgId, avgDimension){
var node, w, h, oldArea, oldAvgDimension, multiplicator, targetHeight, targetWidth, defAvgDimension;
node = $('#' + imgId);
node.css('width', '').css('height', '');
var maxW = $('#' + imgId).css('maxWidth');
if (maxW){
defAvgDimension = maxW;
} else {
defAvgDimension = 200;
}
avgDimension = (typeof avgDimension == "undefined")?'defAvgDimension':avgDimension;
w = node.width();
h = node.height();
oldArea = w*h;
oldAvgDimension = Math.sqrt(oldArea);
if (oldAvgDimension > avgDimension){
multiplicator = avgDimension / oldAvgDimension;
targetHeight = h * multiplicator;
targetWidth = w * multiplicator;
node.width(targetWidth);
node.height(targetHeight);
}
}
function fitImageInArea(img, area) {
var r;
if (img.width/img.height >= area.width/area.height) {
r = area.width / img.width;
img.width = area.width;
img.height = img.height*r;
} else {
r = area.height / img.height;
img.height = area.height;
img.width = img.width*r;
}
return img;
}
Give an image or anything with width and height properties as an argument. area argument assume width and height properties too.

How to resize images proportionally / keeping the aspect ratio?

I have images that will be quite big in dimension and I want to shrink them down with jQuery while keeping the proportions constrained, i.e. the same aspect ratio.
Can someone point me to some code, or explain the logic?
I think this is a really cool method:
/**
* Conserve aspect ratio of the original region. Useful when shrinking/enlarging
* images to fit into a certain area.
*
* #param {Number} srcWidth width of source image
* #param {Number} srcHeight height of source image
* #param {Number} maxWidth maximum available width
* #param {Number} maxHeight maximum available height
* #return {Object} { width, height }
*/
function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {
var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
return { width: srcWidth*ratio, height: srcHeight*ratio };
}
Have a look at this piece of code from http://ericjuden.com/2009/07/jquery-image-resize/
$(document).ready(function() {
$('.story-small img').each(function() {
var maxWidth = 100; // Max width for the image
var maxHeight = 100; // Max height for the image
var ratio = 0; // Used for aspect ratio
var width = $(this).width(); // Current image width
var height = $(this).height(); // Current image height
// Check if the current width is larger than the max
if(width > maxWidth){
ratio = maxWidth / width; // get ratio for scaling image
$(this).css("width", maxWidth); // Set new width
$(this).css("height", height * ratio); // Scale height based on ratio
height = height * ratio; // Reset height to match scaled image
width = width * ratio; // Reset width to match scaled image
}
// Check if current height is larger than max
if(height > maxHeight){
ratio = maxHeight / height; // get ratio for scaling image
$(this).css("height", maxHeight); // Set new height
$(this).css("width", width * ratio); // Scale width based on ratio
width = width * ratio; // Reset width to match scaled image
height = height * ratio; // Reset height to match scaled image
}
});
});
If I understand the question correctly, you don't even need jQuery for this. Shrinking the image proportionally on the client can be done with CSS alone: just set its max-width and max-height to 100%.
<div style="height: 100px">
<img src="http://www.getdigital.de/images/produkte/t4/t4_css_sucks2.jpg"
style="max-height: 100%; max-width: 100%">
</div>​
Here's the fiddle: http://jsfiddle.net/9EQ5c/
In order to determine the aspect ratio, you need to have a ratio to aim for.
function getHeight(length, ratio) {
var height = ((length)/(Math.sqrt((Math.pow(ratio, 2)+1))));
return Math.round(height);
}
function getWidth(length, ratio) {
var width = ((length)/(Math.sqrt((1)/(Math.pow(ratio, 2)+1))));
return Math.round(width);
}
In this example I use 16:10 since this the typical monitor aspect ratio.
var ratio = (16/10);
var height = getHeight(300,ratio);
var width = getWidth(height,ratio);
console.log(height);
console.log(width);
Results from above would be 147 and 300
There are 4 parameters to this problem
current image width iX
current image height iY
target viewport width cX
target viewport height cY
And there are 3 different conditional parameters
cX > cY ?
iX > cX ?
iY > cY ?
solution
Find the smaller side of the target view port F
Find the larger side of the current view port L
Find the factor of both F/L = factor
Multiply both sides of the current port with the factor ie, fX = iX * factor; fY = iY * factor
that's all you need to do.
//Pseudo code
iX;//current width of image in the client
iY;//current height of image in the client
cX;//configured width
cY;//configured height
fX;//final width
fY;//final height
1. check if iX,iY,cX,cY values are >0 and all values are not empty or not junk
2. lE = iX > iY ? iX: iY; //long edge
3. if ( cX < cY )
then
4. factor = cX/lE;
else
5. factor = cY/lE;
6. fX = iX * factor ; fY = iY * factor ;
This is a mature forum, I am not giving you code for that :)
actually i have just run into this problem and the solution I found was strangely simple and weird
$("#someimage").css({height:<some new height>})
and miraculously the image is resized to the new height and conserving the same ratio!
Does <img src="/path/to/pic.jpg" style="max-width:XXXpx; max-height:YYYpx;" > help?
Browser will take care of keeping aspect ratio intact.
i.e max-width kicks in when image width is greater than height and its height will be calculated proportionally. Similarly max-height will be in effect when height is greater than width.
You don't need any jQuery or javascript for this.
Supported by ie7+ and other browsers (http://caniuse.com/minmaxwh).
If the image is proportionate then this code will fill the wrapper with image. If image is not in proportion then extra width/height will get cropped.
<script type="text/javascript">
$(function(){
$('#slider img').each(function(){
var ReqWidth = 1000; // Max width for the image
var ReqHeight = 300; // Max height for the image
var width = $(this).width(); // Current image width
var height = $(this).height(); // Current image height
// Check if the current width is larger than the max
if (width > height && height < ReqHeight) {
$(this).css("min-height", ReqHeight); // Set new height
}
else
if (width > height && width < ReqWidth) {
$(this).css("min-width", ReqWidth); // Set new width
}
else
if (width > height && width > ReqWidth) {
$(this).css("max-width", ReqWidth); // Set new width
}
else
(height > width && width < ReqWidth)
{
$(this).css("min-width", ReqWidth); // Set new width
}
});
});
</script>
This should work for images with all possible proportions
$(document).ready(function() {
$('.list img').each(function() {
var maxWidth = 100;
var maxHeight = 100;
var width = $(this).width();
var height = $(this).height();
var ratioW = maxWidth / width; // Width ratio
var ratioH = maxHeight / height; // Height ratio
// If height ratio is bigger then we need to scale height
if(ratioH > ratioW){
$(this).css("width", maxWidth);
$(this).css("height", height * ratioW); // Scale height according to width ratio
}
else{ // otherwise we scale width
$(this).css("height", maxHeight);
$(this).css("width", height * ratioH); // according to height ratio
}
});
});
Here's a correction to Mehdiway's answer. The new width and/or height were not being set to the max value. A good test case is the following (1768 x 1075 pixels): http://spacecoastsports.com/wp-content/uploads/2014/06/sportsballs1.png. (I wasn't able to comment on it above due to lack of reputation points.)
// Make sure image doesn't exceed 100x100 pixels
// note: takes jQuery img object not HTML: so width is a function
// not a property.
function resize_image (image) {
var maxWidth = 100; // Max width for the image
var maxHeight = 100; // Max height for the image
var ratio = 0; // Used for aspect ratio
// Get current dimensions
var width = image.width()
var height = image.height();
console.log("dimensions: " + width + "x" + height);
// If the current width is larger than the max, scale height
// to ratio of max width to current and then set width to max.
if (width > maxWidth) {
console.log("Shrinking width (and scaling height)")
ratio = maxWidth / width;
height = height * ratio;
width = maxWidth;
image.css("width", width);
image.css("height", height);
console.log("new dimensions: " + width + "x" + height);
}
// If the current height is larger than the max, scale width
// to ratio of max height to current and then set height to max.
if (height > maxHeight) {
console.log("Shrinking height (and scaling width)")
ratio = maxHeight / height;
width = width * ratio;
height = maxHeight;
image.css("width", width);
image.css("height", height);
console.log("new dimensions: " + width + "x" + height);
}
}
$('#productThumb img').each(function() {
var maxWidth = 140; // Max width for the image
var maxHeight = 140; // Max height for the image
var ratio = 0; // Used for aspect ratio
var width = $(this).width(); // Current image width
var height = $(this).height(); // Current image height
// Check if the current width is larger than the max
if(width > height){
height = ( height / width ) * maxHeight;
} else if(height > width){
maxWidth = (width/height)* maxWidth;
}
$(this).css("width", maxWidth); // Set new width
$(this).css("height", maxHeight); // Scale height based on ratio
});
2 Steps:
Step 1) calculate the ratio of the original width / original height of Image.
Step 2) multiply the original_width/original_height ratio by the new desired height to get the new width corresponding to the new height.
Without additional temp-vars or brackets.
var width= $(this).width(), height= $(this).height()
, maxWidth=100, maxHeight= 100;
if(width > maxWidth){
height = Math.floor( maxWidth * height / width );
width = maxWidth
}
if(height > maxHeight){
width = Math.floor( maxHeight * width / height );
height = maxHeight;
}
Keep in Mind: Search engines don't like it, if width and height attribute does not fit the image, but they don't know JS.
After some trial and error I came to this solution:
function center(img) {
var div = img.parentNode;
var divW = parseInt(div.style.width);
var divH = parseInt(div.style.height);
var srcW = img.width;
var srcH = img.height;
var ratio = Math.min(divW/srcW, divH/srcH);
var newW = img.width * ratio;
var newH = img.height * ratio;
img.style.width = newW + "px";
img.style.height = newH + "px";
img.style.marginTop = (divH-newH)/2 + "px";
img.style.marginLeft = (divW-newW)/2 + "px";
}
The resize can be achieved(maintaining aspect ratio) using CSS.
This is a further simplified answer inspired by Dan Dascalescu's post.
http://jsbin.com/viqare
img{
max-width:200px;
/*Or define max-height*/
}
<img src="http://e1.365dm.com/13/07/4-3/20/alastair-cook-ashes-profile_2967773.jpg" alt="Alastair Cook" />
<img src="http://e1.365dm.com/13/07/4-3/20/usman-khawaja-australia-profile_2974601.jpg" alt="Usman Khawaja"/>
This issue can be solved by CSS.
.image{
max-width:*px;
}
Resize to fit the container, get scale factor, scale down percentage control
$(function () {
let ParentHeight = 200;
let ParentWidth = 300;
$("#Parent").width(ParentWidth).height(ParentHeight);
$("#ParentHeight").html(ParentHeight);
$("#ParentWidth").html(ParentWidth);
var RatioOfParent = ParentHeight / ParentWidth;
$("#ParentAspectRatio").html(RatioOfParent);
let ChildHeight = 2000;
let ChildWidth = 4000;
var RatioOfChild = ChildHeight / ChildWidth;
$("#ChildAspectRatio").html(RatioOfChild);
let ScaleHeight = ParentHeight / ChildHeight;
let ScaleWidth = ParentWidth / ChildWidth;
let Scale = Math.min(ScaleHeight, ScaleWidth);
$("#ScaleFactor").html(Scale);
// old scale
//ChildHeight = ChildHeight * Scale;
//ChildWidth = ChildWidth * Scale;
// reduce scale by 10%, you can change the percentage
let ScaleDownPercentage = 10;
let CalculatedScaleValue = Scale * (ScaleDownPercentage / 100);
$("#CalculatedScaleValue").html(CalculatedScaleValue);
// new scale
let NewScale = (Scale - CalculatedScaleValue);
ChildHeight = ChildHeight * NewScale;
ChildWidth = ChildWidth * NewScale;
$("#Child").width(ChildWidth).height(ChildHeight);
$("#ChildHeight").html(ChildHeight);
$("#ChildWidth").html(ChildWidth);
});
#Parent {
background-color: grey;
}
#Child {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Parent">
<div id="Child"></div>
</div>
<table>
<tr>
<td>Parent Aspect Ratio</td>
<td id="ParentAspectRatio"></td>
</tr>
<tr>
<td>Child Aspect Ratio</td>
<td id="ChildAspectRatio"></td>
</tr>
<tr>
<td>Scale Factor</td>
<td id="ScaleFactor"></td>
</tr>
<tr>
<td>Calculated Scale Value</td>
<td id="CalculatedScaleValue"></td>
</tr>
<tr>
<td>Parent Height</td>
<td id="ParentHeight"></td>
</tr>
<tr>
<td>Parent Width</td>
<td id="ParentWidth"></td>
</tr>
<tr>
<td>Child Height</td>
<td id="ChildHeight"></td>
</tr>
<tr>
<td>Child Width</td>
<td id="ChildWidth"></td>
</tr>
</table>
Resizing an image to a certain percentage
// scale can be 0.40, 0.80, etc.
function imageScaler(originalHeight, originalWidth, scale) {
const scaledWidth = originalWidth * scale;
const scaledHeight = (originalHeight / originalWidth) * scaledWidth;
return [scaledHeight, scaledWidth];
}
You can determine width height if you want a particular aspect ratio to do so,
Let you have a picture of 3264×2448
Pictures aspect ratio is => 2448 ÷ 3264 =0.75
Now just check number which gives 0.75 on division.
Like: for
16:9 => 9÷16 =0.5625 (wrong it is not 0.75)
Now 4:3 =>3÷4=0.75 (we get it )
So the original aspect ratio is 4:3
now to resize the image just do
Width=3264 ÷/× 4
Height=2448 ÷/× 3
÷ for reducing
× for increasing
Hope you can understand and code yourself this is very effective because we just need to do very basic arithmetic just division or multiplication so simple.
Let me know if i am wrong.
This totally worked for me for a draggable item - aspectRatio:true
.appendTo(divwrapper).resizable({
aspectRatio: true,
handles: 'se',
stop: resizestop
})

Categories

Resources