Change element dimensions with the ratio another element changed with - javascript

In this example:
Fiddle Example
I have a Picture with dimensions 835x470, That image is added to 2 elements, A hidden <img> and as a background to a <div> width class wrapper, I set the <div> dimensions to smaller dimensions 519x220 on my screen.
There is a centered circular element on the <div> with the dimensions 100x100, I want to set these dimensions with the same ratio the image changed from 835x470 to 519x220.
So for example if the circle on the original image 835x470 was 200x200, When the <div> dimensions are set/changed to 519x220, The circle would take the same space it took on the original image, Which were 200x200.
So if the 200x200 represented 15% for example from the 835x470, Then the circle would take the same 15% from the new dimensions 519x220
What I tried to do is that I get the natural dimensions of the image 835x470 and get the new dimension of the image 519x220 and divide each dimension to get a ratio, Then check to get the smallest ratio (Not to make the circle be out of the image), Then multiply this ratio by 200 and set it as width and height of the image.
Here is the code:
//Get natural dimensions from the hidden image.
var imgNaturalHeight = document.getElementById('img').naturalHeight,
imgNaturalWidth = document.getElementById('img').naturalWidth,
//Get new dimensions from the wrapper that has the image as a background.
imgNewHeight = document.querySelector('.wrapper').height,
imgNewWidth = document.querySelector('.wrapper').width,
//Get height and width ratios.
widthRatio = imgNewWidth / imgNaturalWidth,
heightRatio = imgNewHeight / imgNaturalHeight,
//Define ratio variable.
ratio;
//Set ratio to the smallest ratio.
if ( widthRatio < heightRatio ) {
ratio = widthRatio;
}else{
ratio = heightRatio;
}
//The new value for width and height
var fixed = ratio * 200;
//Set the new width and height of the circle.
document.querySelector('.overlay').style.width = fixed;
document.querySelector('.overlay').style.height = fixed;
.wrapper{
position: relative;
background: url('https://raw.githubusercontent.com/fengyuanchen/cropperjs/master/docs/images/picture.jpg');
height:220px;
background-repeat: no-repeat;
background-size: 100%;
}
.overlay{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
background: rgba(0,0,0,0.4);
border-radius: 50%;
width: 100px;
height: 100px;
}
.image{
display:none;
}
<div class="wrapper">
<div class="overlay"></div>
</div>
<img id="img" class="image" src="https://raw.githubusercontent.com/fengyuanchen/cropperjs/master/docs/images/picture.jpg" >
I hope I made it clear.

So that it takes the same space it took on the original image, Which were 200x200.
Try to follow this steps:
calculate ratio of new to old image with and height
multiply original circle dimensions by its ratio
This should do the trick.
There is some example (maybe not exactly your case but I hope you can adapt it easily).
Example
Note: Im not so sure what you try to achieve in pure JS so I used clientHeight property, you can read about other possibilities here Height and width in JS

//Get natural dimensions from the hidden image.
var imgNaturalHeight = document.getElementById('img').naturalHeight,
imgNaturalWidth = document.getElementById('img').naturalWidth,
//Get new dimensions from the wrapper that has the image as a background.
imgNewHeight = document.querySelector('.wrapper').clientHeight,
imgNewWidth = document.querySelector('.wrapper').clientWidth,
//Get height and width ratios.
widthRatio = imgNewWidth / imgNaturalWidth,
heightRatio = imgNewHeight / imgNaturalHeight,
//Define ratio variable.
ratio;
//Set ratio to the smallest ratio.
if ( widthRatio < heightRatio ) {
ratio = widthRatio;
}else{
ratio = heightRatio;
}
//The new value for width and height
var fixed = ratio * 200;
//Set the new width and height of the circle.
document.querySelector('.overlay').style.width = fixed + "px";
document.querySelector('.overlay').style.height = fixed + "px"

Related

Resize canvas to whole screen after it was drawn

I am writing a simple game in javascript which draws on a HTML canvas. The canvas has a fixed size (1280 × 720) and that is also the "room" in which the objects are drawn.
Now I want the canvas to be stretched to be 100 % of the screen. I can't do that by just setting the width and height of the canvas because the javascript would only draw in the 1280 × 720 rectangle in the top left.
What I want instead is, that it is zoomed in so that it takes up the whole screen and if the javascript draws something at (1280, 720) it should be the bottom right corner.
Can I do this without using any external libraries?
If you wish to keep the rendering size at 1280x720 for the canvas, but stretch or expand it to the window size you can use the css width and height for that.
Using css will only cause the shape of the canvas to change, but the internal pixels/drawing frame are still set by the width and height attribute. (This will of course cause the image to be blurry if it is upscale to much)
With CSS:
* { margin: 0; padding: 0;}
body, html { height:100%; }
#canvasID {
position:absolute;
height:100%;
/*width:100%; /* uncomment if you don't care about aspect ratio*/
}
<canvas id="canvasID" width=128 height=72>
With a script:
$(document).ready(function() {
function resizeCanvas() {
var canvas = $("#canvasID");
// original width/height from the canvas attribute
var heightOriginal = canvas[0].height;
var widthOriginal = canvas[0].width;
// fill to window height while maintaining aspect ratio
var heightNew = window.innerHeight;
// replace with window.innerWidth if you don't care about aspect ratio
var widthNew = heightNew / heightOriginal * widthOriginal;
canvas.css("height", heightNew + "px");
canvas.css("width", widthNew + "px");
}
// keep size when window changes size
$(window).resize(resizeCanvas);
// initial resize of canvas on page load
resizeCanvas();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvasID" width=128 height=72>
Alternately if you wish for the internal canvas resolution/size to be able to change dynamically you can use scale to ensure that everything gets rendered to the right size.
$(document).ready(function() {
var canvas = $("#canvasID");
// original width/height from the canvas attribute
var heightOriginal = canvas[0].height;
var widthOriginal = canvas[0].width;
// current scale (original 1 to 1)
var verticalRatio = 1;
var horizontalRatio = 1;
// the canvas context
var ctx = canvas[0].getContext('2d');
function setScale() {
// remove previous scale
ctx.scale(1/horizontalRatio, 1/verticalRatio);
// fill to window height while maintaining aspect ratio
var heightNew = window.innerHeight;
// not needed if you don't care about aspect ratio
var widthNew = heightNew / heightOriginal * widthOriginal;
// these would be the same if maintaining aspect ratio
verticalRatio = heightNew / heightOriginal;
horizontalRatio = widthNew / widthOriginal;
// update drawing scale
ctx.scale(horizontalRatio, verticalRatio);
// update width and height of canvas
canvas[0].height = heightNew;
canvas[0].width = widthNew;
}
// keep size when window changes size
$(window).resize(setScale);
// initial resize of canvas on page load
setScale();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvasID" width=128 height=72>

How to scale div's contents with the div?

I have a parent div that contains an image with a bunch of "holes" in it. I have a child div for each hole that defines the exact size of those holes. In the holes, I have text that I've set to position:absolute so that they fit exactly in the holes. However, when I resize the parent div, the contents don't scale at all and they stay the same size. They're also not inside the holes anymore.
User '%' as a unit instead of pixel
<div id="ParentDiv">
<img src="../610614-spring-forest.jpg">
<div class="hole1">Tree1</div>
</div>
#ParentDiv{
max-width:900px;
position: relative;
}
img{
width: 100%;
height: auto;
}
.hole1{
position: absolute;
left:2.75%;
top:23.87%;
}
You can use Viewport Hieght or Viewport Width unit for that case. Below is the example how you could use.
#ParentDiv{
max-width:100vw;
max-height:100vh;
position: relative;
}
img{
width: 100%;
height: auto;
}
.hole1{
position: absolute;
/*left:2.75%;
top:23.87%;*/
left:2.75vw;
top:23.87vh;
}
Try to use similar, hope you will get the desired result.
You could use a CSS property called transform instead of directly changing the size.
When you need to set the size of the image:
// this is the container the image and its text is in
imageContainer = document.getElementById('myDiv');
// original size of image
origX = 400;
origY = 300;
// size you need it to change to
newX = 800;
newY = 600;
/*
Tells CSS to stretch from the top-left edge of the object, so it won't stretch off the left side of the screen
Best way to change value would be percentages
Value of '0 0' sets origin to top-left
Value of '100% 100%' sets origin to bottom-right
*/
imageContainer.style.transformOrigin = '0 0';
//the following is just one string, broken into multiple lines for easy explanation
// tells CSS that the transform type is scale
imageContainer.style.transform = 'scale(' +
// tells CSS how many times normal size to widen image. in this case evaluates to 2, since 800/400 is 2, making image 2x wider
(newX / origX) + ',' +
// tells CSS how many times normal size to heighten image. in this case evaluates to 2, since 600/300 is 2, making image 2x taller
(newY / origY) + ')';
Assuming you have no major performance-sapping functions, this will work great. It's just a little slow if you have loads of stuff going on.
Uncommented:
imageContainer = document.getElementById('myDiv');
origX = 400;
origY = 300;
newX = 800;
newY = 600;
imageContainer.style.transformOrigin = '0 0';
imageContainer.style.transform = 'scale(' + (newX / origX) + ',' (newY / origY) + ')';

Create a div having its aspect 16:9 while having height 100%

I found many examples where to have width 100% and altering the height to have the aspect to be 16:9, but i'd like to have the div to fill the height and the width to be altered, centered.
Example for height:
Maintain the aspect ratio of a div with CSS
It will create an aspect 16:9 css only, that would be the best.
Did it with jquery, here is my solution.
HTML
<div id="aspect" style="margin:auto; width:100%; height:100%;"></div>
JQUERY
function setAspect(aspect) {
var div = $("#aspect");
div.css("height","100%").css("width","100%");
var height = div.outerHeight(false);
var width = div.outerWidth(false);
var fullaspect = width / height;
if (aspect > fullaspect) {
//adjust height
div.css("height", width / aspect);
} else {
//adjust width
div.css("width", height * aspect);
}
}
setAspect(16/9);
//setAspect(4/3);
//setAspect(1);
Have a nice day.

Keep div overlay relative to background image regardless of window size

I want to overlay some text over a background image with background-size: cover.
Problem here is how do I keep the overlay div at the same position, relative to the background image, regardless of the window's size?
Here's a fiddle to play around: http://jsfiddle.net/resting/2yr0b6v7/
So I want to position the word eye over the eye of the cat, regardless of window size.
CSS or JS solutions are both welcomed.
EDIT: Added js alternative
I was convinced that this could be done with css and almost gave up, but then I remembered the new(ish) css units vh and vw....
jsfiddle
CSS
html, body{
height: 100%;
width: 100%;
}
.cat {
height: 100%;
width: 100%;
position: relative;
background:url(http://placekitten.com/g/800/400) no-repeat center center / cover;
}
.place-on-eye {
position: absolute;
color: #fff;
margin:0;
}
#media (min-aspect-ratio: 2/1) {
.place-on-eye {
bottom: 50%;
left: 46.875%;
margin-bottom: 1.25vw;
}
}
#media (max-aspect-ratio: 2/1) {
.place-on-eye {
bottom: 52.5%;
left: 50%;
margin-left: -6.25vh;
}
}
Explanation
So the left eye is at approx 375, 190, and since the image is centered, we will also want to know how far off the center it is, so 25, 10. Since the image is covering, the size of the image will change based on whether the aspect ratio of the viewport is greater or less than the aspect ratio of the background image. Knowing this, we can use media queries to position the text.
The image is 2:1, so when the viewport aspect ratio is > 2:1, we know that the width of the image is the width of the viewport, so the left position of the <p> should always be 46.867% (375/800). The bottom position is going to be more difficult because the image extends beyond the viewport top and bottom. We know that the image is centered, so first move the <p> to the middle, then push it up by 2.5% (10/400) of the height of the image. We don't know the height of the image, but we do know the image aspect ratio and that the width of the image is equal to the width of the viewport, so 2.5% of the height = 1.25% width. So we have to move the bottom up by 1.25% width, which we can do by setting margin-bottom:1.25vw. Incidentally, we can do this without vw in this case because padding is always calculated relative to the width, so we could have set padding-bottom:1.25%, however this won't work in the next case where you have to position the left relative to the height.
The case when the aspect ratio is < 2:1 is analogous. The height of the image is the height of the viewport, so the bottom position should always be 52.5% (210/400) and the left is calculated similar to above. Move it over to center, then back it up by 3.125% (25/800) the width of the image, which is equal to 6.25% the height of the image, which is equal to the viewport height, so margin-left:-6.25vh.
Hopefully this is correct and helps you out!
JS Alternative
jsfiddle
Here's an alternative that uses js. It uses some features like forEach and bind that might cause problems depending on how old a browser you need it to work on, but they are easily replaceable. With js you can directly calculate the scaled dimensions of the bg image which makes the positioning easier. Not the most elegant code, but here goes:
//elem: element that has the bg image
//features: array of features to mark on the image
//bgWidth: intrinsic width of background image
//bgHeight: intrinsic height of background image
function FeatureImage(elem, features, bgWidth, bgHeight) {
this.ratio = bgWidth / bgHeight; //aspect ratio of bg image
this.element = elem;
this.features = features;
var feature, p;
for (var i = 0; i < features.length; i++) {
feature = features[i];
feature.left = feature.x / bgWidth; //percent from the left edge of bg image the feature resides
feature.bottom = (bgHeight - feature.y) / bgHeight; //percent from bottom edge of bg image that feature resides
feature.p = this.createMarker(feature.name);
}
window.addEventListener("resize", this.setFeaturePositions.bind(this));
this.setFeaturePositions(); //initialize the <p> positions
}
FeatureImage.prototype.createMarker = function(name) {
var p = document.createElement("p"); //the <p> that acts as the feature marker
p.className = "featureTag";
p.innerHTML = name;
this.element.appendChild(p);
return p
}
FeatureImage.prototype.setFeaturePositions = function () {
var eratio = this.element.clientWidth / this.element.clientHeight; //calc the current container aspect ratio
if (eratio > this.ratio) { // width of scaled bg image is equal to width of container
this.scaledHeight = this.element.clientWidth / this.ratio; // pre calc the scaled height of bg image
this.scaledDY = (this.scaledHeight - this.element.clientHeight) / 2; // pre calc the amount of the image that is outside the bottom of the container
this.features.forEach(this.setWide, this); // set the position of each feature marker
}
else { // height of scaled bg image is equal to height of container
this.scaledWidth = this.element.clientHeight * this.ratio; // pre calc the scaled width of bg image
this.scaledDX = (this.scaledWidth - this.element.clientWidth) / 2; // pre calc the amount of the image that is outside the left of the container
this.features.forEach(this.setTall, this); // set the position of each feature marker
}
}
FeatureImage.prototype.setWide = function (feature) {
feature.p.style.left = feature.left * this.element.clientWidth + "px";
feature.p.style.bottom = this.scaledHeight * feature.bottom - this.scaledDY + "px"; // calc the pixels above the bottom edge of the image - the amount below the container
}
FeatureImage.prototype.setTall = function (feature) {
feature.p.style.bottom = feature.bottom * this.element.clientHeight + "px";
feature.p.style.left = this.scaledWidth * feature.left - this.scaledDX + "px"; // calc the pixels to the right of the left edge of image - the amount left of the container
}
var features = [
{
x: 375,
y: 190,
name: "right eye"
},
{
x: 495,
y: 175,
name: "left eye"
},
{
x: 445,
y: 255,
name: "nose"
},
{
x: 260,
y: 45,
name: "right ear"
},
{
x: 540,
y: 20,
name: "left ear"
}
];
var x = new FeatureImage(document.getElementsByClassName("cat")[0], features, 800, 400);
I have done a fiddle borrowing the principles from the 2 answers. Black dot should overlay at the end of the line. But this solution drifts from actual spot a little in certain ratios.
Maybe someone can improve it?
JS:
$(function() {
function position_spot() {
w = $(window).width();
h = $(window).height();
wR = w/h;
// Point to place overlay based on 1397x1300 size
mT = 293;
mL = -195;
imgW = 1397;
imgH = 1300;
imgR = imgW/imgH;
tR = mT / imgH; // Top ratio
lR = mL / imgW; // Left ratio
wWr = w / imgW; // window width ratio to image
wHr = h / imgH; // window height ratio to image
if (wR > imgR) {
// backgroundimage size
h = imgH * wWr;
w = imgW * wWr;
} else {
h = imgH * wHr;
w = imgW * wHr;
}
$('.overlay-spot').css({
'margin-top': h * tR,
'margin-left': w * lR
});
}
$(window).resize(function() {
position_spot();
});
position_spot();
});
According to how you set your background image position and size:
background-position:center center;
background-size:cover;
the center of background image should still be in the center of your screen - that comes in handy as a constant, so just try to do the same with your p.place-on-eye
.place-on-eye {
...
top: 50%;
left: 50%;
}
Right now paragraph's left top corner is in the center of your screen, if you also add width and height properties you can actually pint elements center into the screen's center. So it's like:
.place-on-eye {
...
width:50px;
height:50px;
text-align:center /* to make sure the text is center according to elements width */
top: 50%;
left: 50%;
margin:-25px 0 0 -25px;
}
So now the center of p.place-on-eye is in the exact center of your screen, just like the center of your background image. To get it over the cat's eye just offset the left and top margin as needed.
so something like margin:-27px 0 0 -60px; should do it.
fiddle

How can I proportionally scale down an <img> element with the shorter of its WxH set to a fixed number?

html:
<div id="thumbnail">
<img src="xxx">
</div>
css:
div.thumbnail
{
border: 2px solid #ccc;
width: 50px;
height: 50px;
overflow: hidden;
}
Say the image size is greater than 50x50, is there any way that I can proportionally scale down the image so that the shorter of its width and height would become 50px? Note that the image can be in either portrait or landscape.
First load up the image in javascript to get its real dimensions.
var img = new Image('image.jpg');
var width = img.width;
var height = img.height;
Then determine which one has the larger height, and adjust them accordingly using the ratios.
if (width <= height) {
var ratio = width/height;
var newWidth = 50;
var newHeight = 50 * ratio;
} else {
var ratio = height/width;
var newWidth = 50 * ratio;
var newHeight = 50;
}
Then insert the image into the DOM using jQuery.
$('#imageContainer').append('<img src="' + img.src + '" style="width:' + newWidth + 'px; height:' + newHeight + 'px;" />');
Divide the width of the image by the height, that's your ratio. Then find what's the largest dimension, if it's the width, set the width = 50 * ratio, and height = 50; if it's the height set it height = 50 / ratio and the width = 50. Do you need Javascript code?
You can't constrain an image to a fixed width and height rectangle, while maintaining aspect ratio, in CSS alone. If you need to do this, it will be either a JavaScript or server side solution.
If you set just a width, then the height will be set to maintain the aspect ratio, likewise just a height, but this will not force the image to fit into a box since you can't know which is greatest, the width or the height.
Check out ImageMagick if you'd like something server side, otherwise, consider jQuery for a client side solution. JQuery provides a simple API to let you get the dimensions of any element, which you can then scale programatically. Newer version of ImageMagick also provide simple calls which will allow you to fit an image into a rectangle.

Categories

Resources