"Cropperjs allows users to set a specific height and width for the cropping area when cropping

I am currently utilizing cropper.js on a MVC 5 Razor page where I do not want the user to be able to select the cropping area with the mouse. Instead, I would like to initialize the cropper object with a predefined clipping (selected) area that the user cannot resize, but can move the clipping area on the picture in order to crop a specific part of the image.

Unfortunately, I have not been able to find any option to disable clipping. I checked their GitHub page and it seems like this functionality is not available. Additionally, I posted my request on the GitHub page but did not receive any response. I need assistance in finding a workaround to achieve this desired behavior.

        window.onload = function() {

            var Cropper = window.Cropper;
            var URL = window.URL || window.webkitURL;
            var container = document.querySelector('.img-container');
            var image = container.getElementsByTagName('img').item(0);
            var download = ''; 
            var actions = document.getElementById('actions');
            var dataX = 128; 
            var dataY = 72; 
            var dataHeight = 1024; 
            var dataWidth = 576; 
            var dataRotate = 0;  
            var dataScaleX = -1; 
            var dataScaleY = 1;  
            var options = {
                aspectRatio: 16 / 9,
                preview: '.img-preview',
                ready: function (e) {
                    console.log(e.type);
                },
                cropstart: function (e) {
                    console.log(e.type, e.detail.action);
                },
                cropmove: function (e) {
                    console.log(e.type, e.detail.action);
                },
                cropend: function (e) {
                    console.log(e.type, e.detail.action);
                },
                crop: function (e) {
                    var data = e.detail;

                    console.log(e.type);
                    dataX.value = Math.round(data.x);
                    dataY.value = Math.round(data.y);
                    dataHeight.value = Math.round(data.height);
                    dataWidth.value = Math.round(data.width);
                    dataRotate.value = typeof data.rotate !== 'undefined' ? data.rotate : '';
                    dataScaleX.value = typeof data.scaleX !== 'undefined' ? data.scaleX : '';
                    dataScaleY.value = typeof data.scaleY !== 'undefined' ? data.scaleY : '';
                },
                zoom: function (e) {
                    console.log(e.type, e.detail.ratio);
                }
            };

            var cropper = new Cropper(image, options);
        }
    .img-container {
        min-height: 497px;
        max-width: 497px;
        margin-bottom: 1rem;
        background-color: white;
        text-align: center;
        width: 100%;
    }

    .img-container > img {
        max-width: 100%;
    }

    img {
        vertical-align: middle;
        border-style: none;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.5/cropper.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.5/cropper.css" rel="stylesheet"/>

<div class="img-container">
    <img src="https://images.pexels.com/photos/266011/pexels-photo-266011.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260" id="croppr" />
</div>

Answer №1

Thanks to the assistance from @Chris W., I successfully configured a fixed clipping area.

        var image = document.getElementById('croppr');
        var cropper = new Cropper(image, {
            dragMode: 'move',
            aspectRatio: 16 / 9,
            autoCropArea: 0.65,
            restore: false,
            guides: false,
            center: false,
            highlight: false,
            cropBoxMovable: true,
            cropBoxResizable: false,
            toggleDragModeOnDblclick: false,
        });
    .img-container {
        min-height: 497px;
        max-width: 497px;
        margin-bottom: 1rem;
        background-color: white;
        text-align: center;
        width: 100%;
    }

    .img-container > img {
        max-width: 100%;
    }

    img {
        vertical-align: middle;
        border-style: none;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.5/cropper.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.5/cropper.css" rel="stylesheet"/>

<div class="img-container">
    <img src="https://images.pexels.com/photos/266011/pexels-photo-266011.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260" id="croppr" />
</div>

Answer №2

This method has been effective for me

CSS

.cropped-img-container {
    width: 100%;
}

.cropped-img-container>img {
    max-width: 100%;
}

.object-fit-contain {
    object-fit: contain !important;
}

HTML

<div class="cropped-img-container text-center">
    <img id="cropped-image" src="path_of_your_image" class="w-100 object-fit-contain" height="500" />
 </div>

Answer №3

My issue was resolved with this solution

minHeight: h,
minWidth: w,
maxHeight: h,
maxWidth: w,

Alternatively

        minHeight="200"
        minWidth="200"
        maxHeight="200"
        maxWidth="200"

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

Issue with utilizing display: table and overflow: hidden in Internet Explorer and Firefox, functioning properly on Webkit and Blink

JSFiddle : http://jsfiddle.net/h7xvr2t9/2/ I have been experimenting with ways to achieve some effects: Animating a hidden DIV to slide into view from below a visible container Centering text/image on a link to trigger the animation HTML <div clas ...

What is the best way to calculate the product of decimal numbers within a TypeScript Number variable?

Imagine you have a number, for example 288.65, and you want to multiply it without the decimal point in order to obtain the result of 28865. However, when attempting to achieve this by using console.log(288.65 * 100), the output is not as expected, showin ...

What would you name this particular element?

I want to create a unique slider design but I'm unsure where to begin or how to search for information because I don't know the correct terminology. Does this type of slider have a specific name? I heard about Marquee, but that seems like someth ...

Tips for sending a JavaScript parameter to PHP

I am implementing a pop-up modal window that retrieves data from the myForm and saves the email field value to a JavaScript variable in index.php. How can I pass this JavaScript value to PHP and display it using echo, without refreshing the index.php windo ...

Is there a workaround for Angular ui-sref param removing spaces?

Looking for help with an anchor tag: <a ui-sref="view({id:{{ id }}})" data-toggle="tooltip" data-placement="top" title="View Details"><i class="fa fa-search-plus fa-2x icon-color"></i></a> The issue I'm facing is with the id ...

Exploring the power of Vue i18n for prop translations in Vue applications

My goal is to translate the titles passed to my component through props. However, it seems that these strings are not being translated like the rest of my code due to being passed as props. Below are the two components I am currently working with: Parent ...

Issue: Package Not Found Error during Meteor.js app bundling

When I'm bundling my Meteor app using Meteor UP's mup deploy, I encounter a series of errors listed below. Is it necessary for me to manually install these packages, possibly globally, using Meteorite before proceeding with the bundling process? ...

iPad Exclusive Issue with Scrolling Bug

We recently launched a website for a local restaurant and we've resolved most of the bugs. The only issue remaining seems to be occurring on the Mobile Safari browser on iPads. There is a background selector located at the bottom of the page. When us ...

Issues may arise in TypeScript when you are working with an array of objects along with other properties within a type

I am encountering an issue with an object structure similar to the one below: let Obj = { ['0'] : { mode: 'x' }, getMode: () => 'x' } The problem arises when I attempt to create a type definition as shown here: type Obj = ...

How to link a JavaScript file within a PHP document

I have an HTML file (index.html) that is using JavaScript to call a PHP file (pdj.php) and display the output in a div (pdj), which is functioning correctly. $.ajax({ url: '../command/pdj.php', type: "POST", data: ({xparam: xpara ...

This Javascript task has me completely baffled

What I am striving to achieve is the construction of a program that prompts users to input their grades for various assignments, exams, and projects. The breakdown of points for each component is as follows: 1) Assignment 1 - 25 points 2) Assignment 2 - 2 ...

Experience seamless transitions with Material UI when toggling a single button click

When looking at the examples in the Material UI Transitions documentation, I noticed that there are cases where a button triggers a transition. In my scenario, I have a button that triggers a state change and I want the previous data to transition out befo ...

Using regular expressions, you can locate and replace the second-to-last instance of a dot character in an email address

I'm looking to replace the second last occurrence of a character in a given string. The length of the strings may vary but the delimiter is always the same. Here are some examples along with my attempted solutions: Input 1: james.sam.uri.stackoverflo ...

Error: Unable to call this.loadCategories function in React due to uncaught TypeError in Promise

Currently, I am working on a React application. I encountered an error in the handleCategoryUpdated function. Can you help me figure out why? The error message reads: categoryManager.jsx:22 Uncaught (in promise) TypeError: this.loadCategories is not a fu ...

What is limiting jQuery from triggering events following an Ajax refresh?

Within my ASP.NET project, there exists a partial class housing three radio buttons. Contained within this partial view is the following information: _PartialTEST.cshtml @model FreeLance.Web.Models.PArtialTESTModel @Html.RadioButtonFor(m => m.D1, "t ...

What are the steps to create fixed Angular Material Chips?

I'm currently attempting to achieve a similar look and functionality as demonstrated here: https://material.angularjs.org/1.1.9/demo/chips#static-chips where the chips are static and not selectable, clickable, or hoverable. However, I am utilizing Ang ...

Error: The function $(...).ekkoLightbox is not defined

Recently, I attempted to integrate ekkolightbox into my WordPress website. However, each time I selected an image, I encountered the following error message: Uncaught TypeError: $(...).ekkoLightbox is not a function Initially, I suspected that the issue ...

Vue.js is throwing an error because it cannot find the property or method "blah" when referencing it during rendering

Can you explain why Vue 2 throws an error indicating that a prop is not defined, even though it is statically defined in the parent template? Note: This error does not occur when I include the JavaScript code within the .vue file's script tag instead ...

Having trouble getting async and await to function properly

Why is my code not waiting for validation and running the else part immediately? Can you help me find the mistake? async validateBeforeSubmit(event) { await this.$validator.validateAll().then(result => { if (result) { ...

The AJAX error message states: "Failed to fetch. The request origin 'null' is not allowed by Access-Control-Allow-Origin when trying to load http://localhost/mpl

Similar Question: XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin New to the world of JavaScript, Phonegap, and AJAX here. I'm working on a basic Phonegap application that needs to request a message from a server, ...