Guidelines for centering 2 images with JavaScript

I am faced with a unique challenge involving 2 images, where one image has a designated Mask area and the other image is supposed to be visible through the Masked area of the first image. My goal is to align the second image in the center of the Mask area of the first image.

My current approach involves scaling the second image to match the dimensions of the mask area using the following function (which includes 3 lines of code aimed at alignment, but unfortunately, they did not yield the desired results),

function scaleimage(img){

    img.style.height = 'auto';
    img.style.width = 'auto';

    //Obtaining the dimensions of the image
    var imgW = img.clientWidth;
    var imgH = img.clientHeight;

    //Obtaining the dimensions of the mask
    var maskH = data.result.mask.maskhight;
    var maskW = data.result.mask.maskwidth;

    var scaleH = maskH / imgH;
    var scaleW = maskW / imgW;

    // Scaling the image
    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";
    }

    //Attempting to align the image - the following code was tried without success

    /*img.style.top = Math.round((mask1H - imgH) / 2) + 'px';
    img.style.left = '50%';
    img.style.marginLeft = Math.round(imgW/2) + 'px'; */

}

To further illustrate, the current and expected result involves IMAGE 1 with a Mask area revealing IMAGE 2 positioned behind it, with IMAGE 2's top left aligned with the Mask area's top left. Ultimately, the goal is for IMAGE 2 to be centered within the Mask area.

I have attempted various methods without achieving the desired outcome. Any feedback or suggestions would be greatly appreciated.

Answer №1

It appears that you are looking to resize an image to fit into a mask based on your code. I have created a demo showcasing this functionality using your provided function here. Since I do not have access to your actual HTML, I used my own code with predetermined values for maskW and maskH.

Furthermore, it is important to note that you may need to adjust the position property of the image element to something other than the default value of static if you wish to manually layout it. In the demo, I set the position value of the img element to absolute.

Answer №2

If you're interested, there is a CSS solution you can try out:

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%;
}

Check out the demo here

Answer №3

There are at least two methods that can be utilized in this situation:

  • One approach is to apply a negative left margin to the second image.

    <img id="img"/><img id="mask"/>
    <script>
    mask.style.marginLeft = (imgW + maskW) / -2;
    mask.style.marginTop = (imgH - maskH) / 2;
    </script>
    
  • Another method involves displaying the images as backgrounds of two nested divs. Set the width and height of both divs to be the same as the dimensions of the larger image, and utilize center alignment for the inner background. If utilizing AJAX to fetch the images, remember to also retrieve their sizes.

    <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 concept is just a suggestion and may require adjustments to function properly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for showing both label and value on a pie slice in Apex charts

I am currently utilizing apex chart within an angular application to showcase charts. I am specifically focusing on a pie chart and aiming to customize it by displaying labels on the values within each slice of the pie, similar to what is shown in the atta ...

Clicking on the LI element will automatically trigger a click event on the input radio button

Whenever I click on an li element, I want the corresponding radio input to be selected. However, when I try to do this, I'm seeing an error in the console log: Uncaught RangeError: Maximum call stack size exceeded How can I resolve this issue? Bel ...

How to Alter Button Color upon Click in React with Bootstrap?

I'm working on implementing a thumbs up and thumbs down feature similar to Reddit's upvote and downvote system. The goal is to change the color of the object to green when the thumbs up is clicked and to red when the thumbs down is clicked. How ...

Exploring the CSS transitions using jQuery to create fade-in fade-out effects

I'm currently developing an app using Cordova and incorporating jQuery effects like fadein and fadeout. However, I've noticed that these effects are quite slow on my android device. To address this, I'm considering converting them to CSS and ...

Troubleshooting issues with filtering two MongoDB arrays in ES6 and finding a solution

I have a scenario where I am requesting two arrays of objectIDs from MongoDB, and then attempting to identify the differences between the two arrays. In addition, I am passing these arrays through express middleware using res.locals. Below is the code sn ...

Error in sending data to the server via the specified URL: "Http failure response for http://localhost/post.php: 0 Unknown Error" and POST request to http://localhost/post.php failed with error code

Feeling a bit stuck trying to add data to my database. As a junior with PHP and Angular, I am using PHP via XAMPP and Angular 8. Is it possible to create separate files for the post and get methods in the PHP file? app.component.ts import { Component, O ...

What is the best way to determine if any of the list items (li's) have been marked as selected?

<div id='identifier'> <ul id='list'> <li id='1' class="">a</li> <li id='2' class="">a</li> <li id='3' class="">a</li> <li id='4' class=" ...

"Encountered an issue with ng-annotate during processing

I'm attempting to utilize ng-annotate on my Angular application, but it seems to be not working at all. Here is the configuration part: (function () { 'use strict'; angular.module('app') .config(/*@ngInject*/ ro ...

The functionality of AJAX is hindered in the browser when attempting to fetch data from a URL

Lately, I've been encountering a strange issue when trying to fetch data from a URL. $.ajax({ url: 'URLHERE', dataType: 'html', success: function(data) { //function 2 var xml = $.parseXML(data) $(xml).find('StopLoca ...

Why is it that the condition of being undefined or not functioning properly in state?

I am currently facing an issue with a piece of code I wrote in React JS. The state variable is not functioning as expected and even after modifying it upon button click, nothing seems to be working. After checking the console, I noticed that the state rema ...

When transferring files using formData via axios, the server is unable to interpret the data

`` In my quest to figure out how to send a file from a client using an input type=file to an API, I came across the suggestion to use formData. Following some examples I found, I implemented this approach, but upon checking the data on the server side, it ...

Conceal the element at all times

I'm facing a challenge with a paragraph element that is dynamically filled with content using Javascript. I need to hide the element whenever it doesn't have any text within it. However, I want to avoid using setTimeout or setInterval for this ta ...

Identify and track colored dots within an image using tracking.js

I'm working on creating a program that can tally the number of dots on dominoes in an image, such as the one shown here: https://i.sstatic.net/NKHXl.jpg My goal is to develop this functionality using JavaScript. I've attempted to learn how to u ...

Navigation issues in Internet Explorer appear to be causing problems

I've been working on a new website template design and decided to incorporate a click navigation menu for added functionality (with a javascript fallback for accessibility). I found the menu design on Toddmotto.com and it worked perfectly in most bro ...

Guide: Previewing uploaded images with HTML and jQuery, including file names

Any constructive criticism and alternative methods for accomplishing this task are welcomed. I am currently working on writing jQuery code that will allow users to preview file(s) without reloading the DOM. To achieve this, I have been using .append() to ...

Preparing my JSON data for visualization on a chart

I have successfully retrieved data using this API, but now I need to transform it into a chart within my react project. As a newcomer to JS and React, I am struggling to create a chart with the JSON data. My objective is to display prices by bedrooms over ...

Revamp the Design Layout of a Drag-and-Drop Tool

After experimenting with a drag and drop feature using jQuery, I discovered the following useful code snippet. Here's how it functions: $( "#sortable1, #sortable2" ).sortable({ connectWith: ".connectedSortable" }).disableSelection(); #so ...

Generate a series of rotations ranging from -60 to 60 using d3.cloud

I need help replicating the word cloud feature found on for my website. After studying examples and referencing a Stack Overflow answer, I put together the following code: var fill = d3.scale.category20(); var layout = d3.layout.cloud() .size([900, ...

Removing user mentions in a message using Discord.js V12

I am working on a discord bot using discord.js and I am trying to create a custom *say command. The issue I am facing is that whenever I mention @everyone, or role IDs like <@&542542636743557>, the bot also pings them. Is there a way to replace ...

Assigning event to the body element

Is there a way to bind an event to the entire page, specifically the html or body tag? I am trying to achieve the following: document.addEventListener('mousemove', function() { alert('a'); }); I want an alert to be triggered whenever ...