Cropper.js, effortlessly populating a container with a perfectly centered image

I took inspiration from the cropper.js library website but made modifications. You can check out the original example here.

Here's my version of the modified example: CodePen Link

 var image1
    var cropper1
    var image2
    var cropper2

    function cropperInstances() {
      image1 = document.querySelector('#image1');
      cropper1 = new Cropper(image1, {
        dragMode: 'move',
        aspectRatio: 1 / 1,
        restore: false,
        guides: false,
        center: true,
        highlight: false,
        cropBoxMovable: false,
        cropBoxResizable: false,
        toggleDragModeOnDblclick: false,
        minCropBoxWidth: 300,
        minCropBoxHeight: 300,

      });

      image2 = document.querySelector('#image2');
      cropper2 = new Cropper(image2, {
        dragMode: 'move',
        aspectRatio: 1 / 1,
        restore: false,
        guides: false,
        center: true,
        highlight: false,
        cropBoxMovable: false,
        cropBoxResizable: false,
        toggleDragModeOnDblclick: false,
        minCropBoxWidth: 300,
        minCropBoxHeight: 300,

      });
    }
    window.addEventListener('DOMContentLoaded', cropperInstances);
.container {
      margin: 100px auto;
      width: 300px;
      height: 300px;
    }

    img {
      max-width: 100%;
    }
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <meta name="viewport"
        content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Cropper.js</title>
  <link rel="stylesheet"
        href="https://srv19859.microhost.com.pl/cropper/css/cropper.css">
</head>

<body>
  <div class="container">
    <img id="image1"
         src="https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Lion_waiting_in_Namibia.jpg/1200px-Lion_waiting_in_Namibia.jpg">
  </div>
  <div class="container">
    <img id="image2"
         src="https://upload.wikimedia.org/wikipedia/de/9/93/Burj_Khalifa.jpg">
  </div>
  <script
          src="https://srv19859.microhost.com.pl/cropper/js/cropper.js"></script>

</body>

</html>

My goal is to have these images fill their respective divs while being centered both vertically and horizontally. The challenge is ensuring that:

  • If the image has a horizontal orientation, its height cannot exceed the div's height
  • If the image has a vertical orientation, its width cannot surpass the div's width.

You can see an example of the desired effect here: Image Example

I've been experimenting with different approaches, but I'm struggling to find a solution. The issue is similar to what's discussed in this post: Panzoom Library and Centered Image Filling Problem

Answer №1

I believe I have found the solution:

function adjustImageSize() {
  var imageArray = [image1, image2]
  var ratio
  imageArray.forEach((element) => {
    var naturalHeight = element.imageData.naturalHeight
    var naturalWidth = element.imageData.naturalWidth
    if (naturalHeight < naturalWidth) {
      ratio = 300 / naturalHeight
      element.zoomTo(ratio)
    } else {
      ratio = 300 / naturalWidth
      element.zoomTo(ratio)
    }
  })
}

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

Using JavaScript to Filter Through Numerous Values Based on Different Attributes

My goal is to efficiently filter multiple attributes with multiple values 'arr' represents a list of all products, and 'f_...' indicates the attribute such as color or type. 'namet' denotes the selected attribute by the user ...

Challenges with navbars and Bootstrap

Just started using twitter-bootstrap and I'm trying to customize the navbar by removing borders and padding, adding a hover effect for links with a different background color, and setting margins of about 10px on the left and right. However, I'm ...

Borders are absent on several div elements

There is a strange issue I'm facing where some borders on identical divs are not showing up. I have spent hours trying to troubleshoot this problem, and it seems like zooming in or out sometimes makes the border appear or disappear. My hunch is that i ...

Glass-pane or angular/HTML overlay on a designated element

Is there a way to create a glass-pane effect, like an hourglass symbol on a semi-transparent layer, within the boundaries of an HTML element E? The goal is to have the glass-pane only overlap the area within E's boundaries. When the glass-pane is ac ...

Retrieve posts from Angularjs

I am attempting to fetch tweets from a Twitter account using only AngularJS without the use of PHP or any other programming language. I have made several attempts but have not been successful. Additionally, I must utilize the 1.1 version of the Twitter A ...

The controller is unable to retrieve the posted value

Whenever I try to retrieve the post value from my controller, it always returns null. Even though I can see that there is a post value present when I check, for some reason, I am not able to access that value in my controller. Does anyone know what the p ...

Is there a way to link the scrolling of two ag-grid data tables together for synchronized movement?

I have integrated ag-grid into my Angular project and I am looking to display two data tables (ag-grid) stacked on top of each other. Both data tables should scroll together, meaning when I scroll in table 1 or table 2, the content of both tables should m ...

"Encountering issues with running a MongoDB aggregate query involving date fields

I have been attempting to retrieve data from MongoDB using an aggregate query in Node.js for a specific date range. let date = '20230925' let year = date.slice(0, 4); let month = String(date.slice(4, 6)).padStart(2, '0'); ...

Removing the Tawk.to integration in React Redux using external JavaScript

Seeking help with integrating the Tawk.To Widget into my React APP. The widget (javascript) loads successfully when the page is first opened, but remains present when navigating to another page. How can I properly unmount this script when moving to a diff ...

Reload the Node.js webpage

Is there a method to automatically refresh a Node.js page following a socket.io event? var messageDynamic = "Initial status"; app.get("/", function(request, response) { response.setHeader('Content-Type', 'text/plain'); respons ...

Anomalies observed in label transition while in active state for input field

Can you explain why there is a gap in the label when it's positioned at left:0? I'm aiming to achieve a UI similar to Material design but struggling with label positioning. I've experimented with using translateY(-6px), however, this method ...

Scoped variable in Typescript producing a generated Javascript file

I'm currently learning TypeScript through an online course, and I've encountered a problem that seems to be related to a VSCode setting. Whenever I compile app.ts, it generates the app.js file, but I immediately encounter a TypeScript error. It& ...

Unable to retrieve ajax responseText within a jquery function

Seeking assistance with a form designed for user registration. Utilizing jQuery and AJAX to validate email address availability upon blur event. Employing e.preventDefault(); in JQuery code to prevent form submission in case of errors. However, encounterin ...

Manipulating a global variable in VueJS

Currently, I am referring to Global data with VueJs 2 for my project, focusing on only one variable. In the code provided, I have included an @click event to update the variable. However, it throws an error stating "Uncaught ReferenceError: $myGlobalStuff ...

Managing Data Types in AJAX Requests

Can you help me figure out why my AJAX call is not reaching success after hours of troubleshooting? It seems like the issue lies in the dataType that the AJAX call is expecting or receiving (JavaScript vs JSON). Unfortunately, I'm not sure how to addr ...

Enhance your bootstrap accordion by incorporating stylish up and down arrows using the <accordion> element

I am currently developing a sophisticated web application using Angular and TypeScript, and I have decided to incorporate accordions in some sections. The setup for these accordions involves TypeScript/Bootstrap as shown below: <accordion> <acco ...

What is the process of combining two identical objects in Angular JS?

Is it possible to merge and sort two objects in Angular JS that have the same fields, notifications.fb and notifications.tw, based on their time field? ...

Discovering the XPath of an element

Can anyone help me locate the XPath for the hamburger navigation icon on the website , specifically in the upper left corner? I am developing a Python script using selenium and need it to be able to click this particular button. Here's what I have tr ...

One Page HTML5 with a Bootstrap fixed top menu, revealing content on menu item click

Is there a way to have the Bootsrap mobile menu automatically unfold when a link (anchor on the same page) is clicked? The menu unfolds with class navbar-collapse collapse in The menu folds with class navbar-collapse collapse out I already have an oncl ...

How can we create a two-dimensional image with random dimensions using Math.random?

I am struggling to create a variety of flowers with different sizes from an Array. The issue I'm facing is that every time I click to add a new flower, it changes the size of all existing flowers as well. What I would like is for each added flower to ...