Show only a cropped section of a resized image within a div

I have a script that calculates the best region of an image to display within a specific div size. This calculation is done in PHP and generates a JSON output like this:

{"scale":1.34,"x1":502,"x2":822,"y1":178,"y2":578}

The image in question has dimensions of 1536px width and 1024px height. The target div for displaying this portion of the image is 500px width and 400px height. Despite verifying the accuracy of the PHP calculations, I'm struggling to visually present this image section within the specified div.

My attempt so far involves the following function:

function showImageInDiv(image,data)
{
    imageSrc = image.attr("src");
    data = JSON.parse(data);
    $('#iDiv').empty().append("<img src='"+imageSrc+"' id='iDivImage'>");
    $("#iDivImage").css({
        "position": "absolute",
        "top":0,
        "left":0,
        "height":data.scale+"%",
        "width":data.scale+"%",
        "clip": "rect("+data.y1+"px,"+data.x2+"px,"+data.y2+"px,"+data.x1+"px)"
    }); 
}

Despite implementing the above code with the use of clip, the rendering of the image region remains incorrect within the div. Since I lack expertise in frontend techniques, I am open to alternative methods such as using background-images if it proves more effective. Any guidance on correcting this issue would be greatly appreciated!

Thank you in advance

Answer №1

Not entirely sure about the expected outcome for the values provided below:

{"scale":1.34,"x1":502,"x2":822,"y1":178,"y2":578}

when used in the code snippet:

"rect("+data.y1+"px,"+data.x2+"px,"+data.y2+"px,"+data.x1+"px)"

What will this result in?

Example used:

{"scale":1.34,"x1":100,"x2":200,"y1":100,"y2":200};

You can refer to CanvasRenderingContext2D.drawImage() for more information.

Attempt the following:

var data = {"scale":1.34,"x1":100,"x2":200,"y1":100,"y2":200};
function showImageInDiv(image, data) {   
    $("#iDiv").empty().append("<canvas id=iDivImage width=500px height=400px></canvas>");
    var img = new Image;
    img.onload = function() {
    var canvas = $("#iDivImage");
    var ctx = canvas.get(0).getContext("2d");
    ctx.drawImage(this, data.x1, data.y1, 500, 400, 0, 0, data.x2, data.y2);
    canvas.css("transform", "scale(" + data.scale + ", "+ data.scale +")");
    };
    img.src = image[0].src;    
};

showImageInDiv($("img"), data);

var data = {"scale":1.34,"x1":100,"x2":200,"y1":100,"y2":200};
function showImageInDiv(image, data) {   
    $("#iDiv").empty().append("<canvas id=iDivImage width=500px height=400px></canvas>");
    var img = new Image;
    img.onload = function() {
    var canvas = $("#iDivImage");
    var ctx = canvas.get(0).getContext("2d");
    ctx.drawImage(this, data.x1, data.y1, 500, 400, 0, 0, data.x2, data.y2);
    canvas.css("transform", "scale(" + data.scale + ", "+ data.scale +")");
    };
    img.src = image[0].src;

    //"rect("+data.y1+"px,"+data.x2+"px,"+data.y2+"px,"+data.x1+"px)"

};

showImageInDiv($("img"), data);
#iDiv {
  display:block;
  width:500px;
  height:400px;
}

#iDiv {
  clip-path():
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="iDiv"></div>
<img src="http://lorempixel.com/1536/1024/cats/" />

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

Node.js Apple in-app purchase (IAP) receipt validation

Trying to implement Node.js from this repository for my IAP Receipt Validation, but encountering an error in the server's log: "The data in the receipt-data property was malformed." Seeking assistance on properly sending a base64 string to Node.js an ...

Using Javascript, incorporate a string variable into the response

Currently, I'm working with a node.js program and I've come across this response: 'Content-Disposition': 'attachment; filename="tts.mp3"' Instead of using "tts.mp3," I have a variable named textToConvert. How can I modify it ...

Connecting a text input in a nested component to the data passed down from its parent component in VueJS

My VueJS setup involves a child component sending data to a parent component, which then tries to route the data to a sibling of the child to create new components. I'm using a dictionary to group the data and push it into an array. The array is then ...

An undefined variable was encountered within the 'else' statement

I am encountering an issue with my code where it is returning an 'undefined' error. The problem arises when I attempt to remove an id from an array using the variable 'id', but instead, it throws an error stating 'undefined'. ...

broadcast updated $rootScope

How do I update the $rootScope.$broadcast with a new value? Let's take a look at this code snippet: var test = "fisk"; if(angular.element(this).hasClass('monster')) { var monster_info = angular.element(this).find("img").attr("title"); ...

Having trouble with the installation of nodemon globally on macOS Mojave?

When using the Visual Studio Code terminal, I ran the following command: npm install -g nodemon The output in the terminal showed: npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules npm ERR! code EACCES npm ERR! syscall access n ...

The utilization of the Angular date pipe significantly impacts the way dates are

When I use the pipe date:'MM/dd/YYYY' to display the date 2022-01-01T00:00:00, it shows as 1/01/2021 instead of 1/01/2022. This issue only occurs with this specific date. Why does this happen? The value of pharmacyRestrictionDate is 2022-01-01T0 ...

What is the best way to apply a top padding to a background image using CSS?

I attempted to adjust the top padding using various pixel values in the style, but the image padding relative to the webpage remained unchanged. For example: padding-top: 5px; Here is part of my code snippet: <div class="row pb-5 mt-4" style ...

Deploying tracking scripts within GTM containers during Turbolinks transitions

Is there a solution for getting a Google Tag Manager container to fire all its tags under Turbolinks? In my Rails 4.0 application with Turbolinks, I have included the following code in a footer that is rendered on every page within the <head> tags: ...

Angular tutorial on splitting a JSON array

I am looking to extract a portion of a JSON array in Angular. The array looks like the one in the image below.https://i.stack.imgur.com/w0hqC.png Below is the code snippet: export class AppComponent { color: string = 'green'; public stocklis ...

Obtain abbreviated names for the days of the week starting from Monday to Sunday using JavaScript

Is there a way to retrieve the abbreviated names of each day of the week in JavaScript, starting from Monday through Sunday? ...

PHP is failing to display line breaks when retrieving data from JSON sources

I have a JSON feed that is decoded by PHP using json_decode and then echoed onto my HTML page. The issue I am facing is that the feed contains \n characters, but when PHP echoes them out, they are not recognized as new lines or line breaks in HTML. In ...

Is there a way to share the Username and Password without the need to manually input it?

My goal is to develop a C++ application for my classmates at school. Currently, they are required to visit our school's website and navigate to the login page. Once there, they enter their username and password, log in, and proceed to find their spec ...

Bidirectional Data Binding Using Meteor and React

When using Meteor, the getMeteorData() method is preferred over getInitialState(). But how can we achieve binding, especially with regards to a user's surname in their profile? ... getMeteorData() { return { u = Meteor.user() } }, componentRen ...

Is it possible to store data in a nested object using MongoDB?

I'm having trouble inserting the data from req.body into my mongodb collection. In this route, when the add method is triggered, I am attempting to create a query that will store the data from req.body in a nested collection array. router.post(&apos ...

The JSON POST Method is not allowed for a Self-Hosted WCF REST service

After encountering countless "WCF" questions online, I am starting to believe that finding a solution is nearly impossible. Can someone prove me wrong? My current situation involves working with a Self Hosted WCF Service where endpoints are defined progra ...

The readImage function is not processing the file input correctly

I am struggling with a script that I have created to check the width and height of a selected image file. The problem arises when the script is executed, as it fails to run the code within the function readImage (file) { function, which is supposed to ver ...

Adjusting the background color of an individual element within a grid using CSS

<div id="56c46f8385953" class="mg_box mg_pre_show col1_3 row1_3 m_col1_2 m_row1_3 mgi_14 mg_pag_1 mg_gallery mg_transitions mg_closed " rel="pid_14" mgi_w="0.333" mgi_h="0.333" mgi_mw="0.5" mgi_mh="0.333" > <div class="mg_shadow_div"> ...

Tips for accessing and modifying local JSON data in a Chrome Extension

I am working on an extension and need to access and modify a local JSON file within the extension's directory. How can I accomplish this task? ...

The div is set to a position of absolute, causing the overflow-y property to be set to auto. As a

I am facing an issue with a div that has absolute positioning nested inside other divs. If you take a look at the code snippet below from http://jsfiddle.net/d8GYk/, you'll notice the styling properties applied to the div. <div style="position: ...