How to align 2 images by their centre using JavaScripts - javascript

I have 2 images, one of them has a Mask area. And the other image can be seen through the Masked area of the above image. I want to centre the second image within the Mask area of the first image.
Currently I'm do scale the image to mach with the mask area using below function (It has 3 lines of code that I tried to with alignment - didnt work though),
function scaleimage(img){
img.style.height = 'auto';
img.style.width = 'auto';
//Getting the image hight and width
var imgW = img.clientWidth;
var imgH = img.clientHeight;
//Getting the mask hight and width
var maskH = data.result.mask.maskhight;
var maskW = data.result.mask.maskwidth;
var scaleH = maskH / imgH;
var scaleW = maskW / imgW;
// Scaling
if (scaleH < scaleW) {
img.style.height = maskH + "px";
img.style.width = Math.round(imgW * scaleH) + "px";
} else {
img.style.width = maskW + "px";
img.style.height = Math.round(imgH * scaleW) + "px";
}
//Align image - commented below code since it didnt work
/*img.style.top = Math.round((mask1H - imgH) / 2) + 'px';
img.style.left = '50%';
img.style.marginLeft = Math.round(imgW/2) + 'px'; */
}
Current and Expected result as an Illustration. IMAGE 1 has a Mask area that can see through, and IMAGE 2 is behind IMAGE 1, but align its top left to the Mask Area's Top left. What I want is, IMAGE 2 centre = Mask Area Centre
I tried few things and didn't get any of them quite right, any feedback would be really helpful

If I understand correctly from your code. You want to resize image to fix into your mask. I have write a demo using your function here. Because I dont know your real HTML, I use my own code with a predefined value of maskW and maskH.
Another thing to note: you should set the position property of the image style to another value than the default static value if you want to layout it manually. In the demo, I set the position value of img element to absolute.

There is a css solution for this if you'd like to try:
Html:
<div>
<img class="image" src="http://dummyimage.com/300x200/0000ff/ffffff&text=image" alt="image">
</div>
Css:
div {
width: 150px;
height: 100px;
margin: 50px auto 0;
position: relative;
background: url(http://dummyimage.com/150x100/000/fff&text=mask) no-repeat center center;
}
.image {
width: 80%;
top: 50%;
left: 50%;
position: absolute;
margin: -27% 0 0 -40%;
}
Fiddle

I see at least two approaches here:
use negative left margin of second image
<img id="img"/><img id="mask"/>
<script>
mask.style.marginLeft = (imgW + maskW) / -2;
mask.style.marginTop = (imgH - maskH) / 2;
</script>
show images as background of two divs (one embeds another). Set their width and height same values (of bigger image) and use center alignment of inner background. But then, if you're getting images by AJAX, you should retrieve also sizes of the images.
<div id="img">
<div id="mask"></div>
</div>
<style>
#img {
background-position: top left;
background-repeat: no-repeat;
}
#mask {
width: inherit;
height: inherit;
background-position: center center;
background-repeat: no-repeat;
}
</style>
<script>
var imgDiv = document.getElementsById('img'),
maskDiv = document.getElementById('mask');
imgDiv.style.width = imgW + 'px'; // from AJAX
imgDiv.style.height = imgH + 'px';
imgDiv.style.backgroundImage = "url('img.jpg')"';
maskDiv.style.backgroundImage = "url('mask.jpg')";
</script>
This is juts an idea and should work with fixes

Related

How to make the images uploaded by users meet the size required by the design draft through CSS or JavaScript?

Hello everyone~ I have a problem but my English is not good. I will try my best to express it completely! If the explanation is not clear enough, everyone is welcome to tell me~ The
problem is like this, today there is a block for users to upload photos !
The width and height of this photo after uploading by the user
cannot exceed 360px, the minimum cannot be less than 100px, the
maximum height cannot exceed 200px, and the minimum cannot be less than 100px
.
What I want to ask everyone here is, can this requirement be accomplished only by CSS?
Or can it be accomplished by using JavaScript? But if I use JavaScript, I don't know how to start, because my JavaScript is very poor. I hope I can get your valuable suggestions here, thank you.
I wrote an example. The original picture size is only 50PX in height. How can the height of the photo reach 100PX without affecting the ratio?
.photo{
width: 360px;
height: 200px;
object-fit:contain;
object-position:left center
}
<div class="demo">
<img class="photo" src="https://upload.cc/i1/2021/09/30/s73jb5.jpg" alt="">
</div>
I think this is what you want to do.
Image should have maximum-width to be 360px and minimum height should be 100px.
And also if you want to add min-width and max-height you can add in imageSettings variable in javascript.
If you have multiple images, simply add imageContainerForJS class to img parent element.
(()=>{
let imgContainers = Array.from(document.querySelectorAll('.imageContainerForJS'));
const imageSettings = {
"max-width": 360,
"min-height": 100,
}
for(let imgContainer of imgContainers) {
let img = imgContainer.querySelector('img');
if(!img) continue;
let imageSource = img.src;
let image = new Image();
let maxWidth = imageSettings['max-width'] || null;
let minWidth = imageSettings['min-width'] || 0;
let maxHeight = imageSettings['max-height'] || null;
let minHeight = imageSettings['min-height'] || 0;
image.onload = function() {
let width = this.width;
let height = this.height;
if(maxWidth && width > maxWidth) width = maxWidth;
if(minWidth && width < minWidth) width = minWidth;
if(minHeight && height < minHeight) height = minHeight;
if(maxHeight && height > maxHeight) height = maxHeight;
imgContainer.style.width = width+'px';
imgContainer.style.height = height+'px';
}
image.src = imageSource;
}
})();
.photo{
object-fit: cover;
object-position: center;
width: 100%;
height: 100%;
}
<div class="demo imageContainerForJS">
<img class="photo" src="https://upload.cc/i1/2021/09/30/s73jb5.jpg" alt="">
</div>
You can use object-fit:cover to make your image proportionally expand to fill its container.
Set the container to the dimensions you want, then have the image fill it by setting its width and height be 100%.
By default cover will position the image in the centre.
.demo {
width: 360px;
height: 200px;
}
.demo .photo {
width: 100%;
height: 100%;
object-fit: cover;
/*object-position: left center;*/
}
<div class="demo">
<img class="photo" src="https://upload.cc/i1/2021/09/30/s73jb5.jpg" alt="">
</div>

Trying to set style as screen height and width CSS

What I am trying to do is get the height of the screen and the width of the screen and then use the document.getElement.style.property = newStyle to change the style to the obtained height of the screen and width of the screen. I tried making the height and width into Strings to use, I also tried putting just the values in. I want to know how to put in px values and % values. Thanks.
<!DOCTYPE html>
<html lang = "en/US">
<head>
<title>
cyclebg test
</title>
<style>
body {
background: url("http://i.dailymail.co.uk/i/pix/2016/03/22/13/32738A6E00000578-3504412-image-a-6_1458654517341.jpg")
no-repeat;
background-position: center top;
background-size: 200px 100px;
}
p {
padding: 50px; background-color: green; margin-left: -1%; margin-right: -1%; display: block;
}
</style>
</head>
<body>
<p style = "margin-top: 25%;"> Hello World </p>
<p> Yo </p>
</body>
<script>
var heightOfScreen = screen.height;
var widthOfScreen = screen.width;
var heightOfScreenString = heightOfScreen + " px";
var widthOfScreenString = widthOfScreen + " px";
document.getElementsByTagName("body")[0].style.backgroundSize = "heightOfScreenString widthOfScreenString";
</script>
</html>
You should try using
background-size: cover;
So the background will cover the whole size of the background and cropoff the excess.
If you want the full background to show (despite of blank spaces on top or sides) you can use "contain" instead
https://jsfiddle.net/0vps9x0s/
This shortest & simplest answer is to use CSS to cover the background image and crop the excess, using this:
background-size: cover;
If you want to "fit" the background image to the container, use this:
background-size: 100% 100%;
If you want use jQuery to get the width & height of the window and set the size of the background image, do this:
var width = $(window).width();
var height = $(window).height();
// NOTE: this does the same thing as "background-size: 100% 100%;"
$("body").css("background-size", width + "px " + height + "px");
If you just want to use Vanilla JavaScript to get the width & height of the window and set the size of the background image, use this:
var width = window.innerWidth;
var height = window.innerHeight;
// NOTE: this does the same thing as "background-size: 100% 100%;"
document.getElementsByTagName("body")[0].style.backgroundSize = width + "px " + height + "px";
Good luck and all the best.

Center div horizontally without width with JS

I'm coding my graduate work and I'm having trouble centering div with contents that change change (image upload).
In my script I create <img id="uploaded"> and insert the uploaded image into it, and this <img> is inserted in <div id="canvas"></div>.
In my CSS :
#canvas {
position: absolute;
left: 50%;
z-index: 500;
}
I tried :
var canvaswidth = document.getElementById('uploaded').width;
for getting the img width, and I want to add a negative left margin for centering my div.
I tried :
document.getElementById('canvas').style.marginLeft = - canvaswidth / 2;
But that doesn't work. Can you help me make it work?
You need units:
document.getElementById('canvas').style.marginLeft = - canvaswidth /2 + 'px';
However, you could use "absolute centering":
#canvas {
position: absolute;
left: 0;
right: 0;
margin: auto;
}
And just set the width to the desired value:
document.getElementById('canvas').style.width = canvaswidth + 'px';

FULL bleed video, keep aspect ratio, center, pure javascript

I would like to have my element keep its aspect ratio but act as a 'full-bleed' or rather full browser experience. The video should up or down to accommodate the new browser window dimensions, but also be centered in the browser window. At times, some video will get cropped – that's ok with me. I am trying to recreate the background cover CSS property for the video element using pure JS, if that helps you to imagine it. For those who do not know what that is, heres the following:
.bkgdCover{
background: no-repeat center center;
-webkit-background-size: 100% 100%;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
The following is my attempt to do the same in pure javascript:
function getWinSize(){
var wid = 0, hei = 0;
if (document.documentElement && document.documentElement.clientHeight){
wid = parseInt(window.innerWidth,10);
hei = parseInt(window.innerHeight,10);
} else if (document.body){
wid = parseInt(document.body.offsetWidth,10);
hei = parseInt(document.body.offsetHeight,10);
}
return [wid,hei];
}
this.resize2 = function(){
fullBleedVideoPlayer();
};
function fullBleedVideoPlayer() {
var viewport=getWinSize();
var videoRatio = 1080 / 1920;
var browserHeight = viewport[0];
var browserWidth = viewport[1];
var tmp_windowRatio = viewport[1] / viewport[0];
if (videoRatio > tmp_windowRatio) {
tmp_height = Math.round(browserWidth * videoRatio);
_player.style.width= browserWidth+ "px";
_player.style.height= tmp_height+ "px";
_player.style.marginLeft = 0 + 'px';
_player.style.marginTop = -Math.round((tmp_height - browserHeight) / 2) + 'px';
} else {
tmp_width = Math.round(browserHeight * (1 / videoRatio));
_player.style.width= tmp_width+ "px";
_player.style.height= browserHeight+ "px";
_player.style.marginLeft = -Math.round((tmp_width - browserWidth) / 2) + 'px';
_player.style.marginTop = 0 + 'px';
}
}
Unfortunately, this does not reproduce CSS cover. If you can see where I made a mistake or have done the same yourself, I'd love to hear from you. Only pure JS solutions please.
I just did something like this except it wasn't completely full screen, it was the background video of a page header which had a height of 450px'ish'. I say ish because I'm using 25vw and it's changing height based on viewport width. I basically wanted the video to stay centered, but how?
HTML
<section id="homepage--hero">
<div class="fullpage-video-wrapper">
<video id="video_background" preload="auto" autoplay="true" loop="loop" muted="muted" volume="0">
<source src="http://vjs.zencdn.net/v/oceans.mp4" type="video/mp4">
<source src="http://vjs.zencdn.net/v/oceans.webm" type="video/webm">
<!-- doesnt support video -->
<img src="#" style="width: 100%; height: auto;" />
</video>
</div>
</section>
CSS
#homepage-hero {
display: block;
height: 35vw;
width: 100%;
position:
relative;
overflow: hidden;
}
.fullpage-video-wrapper {
position: absolute;
bottom: 0px;
left: 0px;
min-width: 100%;
min-height: 100%;
width: auto;
height: auto;
z-index: -1000;
overflow: hidden;
}
.fullpage-video-wrapper {
min-height: 100%;
min-width: 100%;
}
JS
if( $('.fullpage-video-wrapper').length > 0 ) {
var videoWrapper = $('.fullpage-video-wrapper'),
videoParentWrapper = $(videoWrapper).parent();
if($(videoWrapper).height() > $(videoParentWrapper).height() ) {
var difference = ($(videoWrapper).height() - $(videoParentWrapper).height()) / 4
$(videoWrapper).css({
bottom: -parseInt(difference)
});
}
$(window).resize(function(){
if($(videoWrapper).height() > $(videoParentWrapper).height() ) {
var difference = ($(videoWrapper).height() - $(videoParentWrapper).height()) / 4
$(videoWrapper).css({
bottom: -parseInt(difference)
});
}
});
}
What this does is makes the video stay the same aspect ratio even when resizing window, positions it to the bottom of the homepage-hero, which this caused it to respond well without causing you to see the background color of the video-wrapper, but obviously not centered.
The jQuery is just setting the videowrapper to be offset the difference in height of the video wrapper element height and it's parent elements height. allowing the aspect ratio to stay the same, bleeding the video when needed but allowing it to be centered in it's parents element vertically.
This was super rough, since I was just working on this about an hour ago, so I'm sure theres plenty I need to rework through and get dialed in, but hopefully this helps you along your path, should be the same solution except your doing your height checks on the video element or video wrap element outerHeight and the viewport height.

Position div to center of visible area

I'm in the midst of making a lightbox style pop-up for a mailing list sign up, but I want the pop-up to position to the center of the visible page, not just the center of the whole document; if the user scrolls to the bottom of the page and clicks to sign up, I want it to appear in the center of the screen.
I'm assuming jQuery/JS will be the best way to go for this; here's my current CSS code which works fairly well but the div needs to be pushed down into the visible space dynamically for smaller screens.
.my-div{
width:960px;
height:540px;
position:absolute;
top:50%;
left:50%;
margin-left:-480px;
margin-top:-270px;
z-index:60;
display:none;
}
You were close! It can be done with CSS alone:
Use position: fixed instead of position: absolute.
Fixed refers to the viewport, while absolute refers to the document. Read all about it!
var w = $(window).width();
var h = $(window).height();
var d = document.getElementById('my-div');
var divW = $(d).width();
var divH = $(d).height();
d.style.position="absolute";
d.style.top = (h/2)-(divH/2)+"px";
d.style.left = (w/2)-(divW/2)+"px";
I know this will not solve the question but it is good reference and a starting point: How to position a div in the center of browser window
Position Div Exactly at the center of the screen
<!DOCTYPE html>
<html >
<head>
<style type="text/css">
.exactCenter {
width:200px;
height:200px;
position: fixed;
background-color: #00FF00;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -100px;
}
</style>
</head>
<body>
<div class="exactCenter"> </div>
</body>
</html>
JSFiddle here
and here
with jQuery:
var left = ($(window).width() - $(.my-div).width()) / 2;
var top = ($(window).height() - $(.my-div).height()) / 2;
$('.my-div').position({top: top + 'px', left: left + 'px});
Although the accepted answer is best, if you can't set the divs position to fixed, then you can use this pure JavaScript solution.
var myElement = document.getElementById('my-div'),
pageWidth = window.innerWidth,
pageHeight = window.innerHeight,
myElementWidth = myElement.offsetWidth,
myElementHeight = myElement.offsetHeight;
myElement.style.top = (pageHeight / 2) - (myElementHeight / 2) + "px";
myElement.style.left = (pageWidth / 2) - (myElementWidth / 2) + "px";
JSFiddle
Or a more condensed version:
var w = window,
elem = document.getElementById('my-div');
elem.style.top = (w.innerHeight/2) - (elem.offsetHeight/2) + 'px';
elem.style.left = (w.innerWidth/2) - (elem.offsetWidth/2) + 'px';
This answer is a vanilla JavaScript version from Lahiru Ashan's answer.

Categories