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

The editor is locked and choices are displayed in a vertical orientation

I'm currently experimenting with using draft js in my project to create a wysiwyg editor. However, I've encountered an issue where the editor appears vertically instead of horizontally when I load the component. Any idea why this might be happen ...

Husky 5: The Ultimate Gitignore Manager

Last week, a new version of Husky was released, known as Husky 5. I came across an interesting article discussing the features and updates in this release that can be found here. Upon migrating to Husky 5 (), I discovered a new directory named .husky with ...

React Application not reflecting recent modifications made to class

My current project involves creating a transparent navigation bar that changes its background and text color as the user scrolls. Utilizing TailwindCSS for styling in my React application, I have successfully implemented the functionality. // src/componen ...

A guide on removing an element from a state array in a React functional component for a To-Do List application

I need help making a to-do list item disappear when clicked. The deleteHandler method is not working as expected. Can anyone provide logic on how to filter out the clicked item? import React, { useState } from 'react'; const ToDoList = () => ...

Applying CSS to prevent elements from overlapping by adjusting their vertical positioning

I need some help with a CSS formatting question. My current setup works well, the menu's position adjusts based on screen size to be centered both vertically and horizontally. However, I'm facing an issue where elements start overlapping if the v ...

Is there a way to automatically generate and allocate an identifier to an input field?

I've written the code below, but I'm having trouble figuring out if it's accurate. Specifically, I can't seem to access the text inputs that have been created by their respective id attributes. for (i=0;i<t;i++) { div.innerHTML=div. ...

Having trouble with Flask not loading images sent through Ajax POST request

When using ajax to post an image, the code looks something like this: // fileData is canvas.toDataURL(fileType); $.ajax({ type: 'POST', url: 'http://ip/api', data: fileData, contentType: false, processData: false, m ...

Eliminate the margin on the subnavigation menu

Hey there, I'm looking to adjust the layout of my menu buttons by removing the left and right "margins" (if that's the correct term), so they all fit neatly inside the navigation bar. I want to ensure that all the menu buttons are able to fit pr ...

An object-c alternative to encodeURIComponent

Having difficulty finding information on this through a search engine. Is there a similar method in Objective-C for encoding URI components? http://www.w3schools.com/jsref/jsref_encodeuricomponent.asp This is a common task, but I am unable to locate any ...

conceal elements using the <option> class隐藏

Although it seems like a simple task, I'm struggling to make it work. I created a form where the user can select a month from a list using the tags: <select> <option> When the selection is changed, the class .gone from the day SELECT is ...

Can we expect React's useState to wait before executing subsequent logic, or will it immediately update the state and trigger a re-render

I have a specific scenario in my code where I am using the useState setter function in React to update a value on line 5. Everything seems to be functioning well without any errors, but I'm curious about something. Since setState updates the state and ...

Dynamic TypeScript class constructor argument typing determined by user input

I am working on creating a dynamic class that can adapt its argument properties based on a certain value. To illustrate this concept, let's consider a simple example: Imagine I have a class called Customizer, and depending on the value of the mode pr ...

"Unexpected discrepancy: Bootstrap Glyphicon fails to appear on webpage, however, is visible

I am having some trouble getting the glyphicon to display properly in my side nav. The arrow head should rotate down, which is a pretty standard feature. Here is the link to the page: The glyphicon should be visible on the "Nicky's Folders" top leve ...

Utilizing a Web Interface for Remote Monitoring of Windows Servers

I am in need of creating a webpage that will indicate whether a server is currently operational or not. These servers are all Windows based, with some running on 2008 and others on 2003. They are spread across different networks within various client locat ...

AngularJs Controller with explicit inline annotation

I usually inject dependencies using inline annotations like this angular.module('app') .controller('SampleController',['$scope','ngDependacy',sampleController]); function sampleController($scope,ngDependacy) { ...

Attempting to insert the symbol "$gt" into a query for a search. {[CastError: Unable to convert value "[object Object]" to date at path "createdAt"]}

In the following code snippet: Reviews.find({createdAt : {"$lt" : app.locals.lastDate}}), I am trying to dynamically change the $lt to $gt. app.post("/scroll", function(req, res){ console.log("req.body...", req.body); var sortCreate = req.body.old ...

adjust variable increment in JavaScript

As I work on developing a Wordpress theme, I have encountered an issue with incrementing a load more button using Javascript. This is my first time facing this problem with a javascript variable, as I don't always use Wordpress. The variable pull_page ...

What is the process for incorporating a no-refresh submission using a hyperlink instead of a button?

Below are a few links that will trigger actions to insert data into different databases once clicked: <a href="#">insert into database1</a> <a href="#">insert into database2</a> <a href="#">insert into database3</a> Th ...

What is the best way to divide widgets in a Wordpress Sidebar?

I am looking to customize the spacing between widgets in my Wordpress sidebar, similar to what is shown on this example site. Currently, my sidebar does not have the desired spacing. I have tried various CSS codes found online, but none of them seem to be ...

Post response not being received by Node.js Express static file on the client side

Greetings all, I'm currently delving into mobile development and seeking to expand my knowledge of the Node.js runtime. As part of my learning process, I have a simple client-side "app" written in JavaScript that I am attempting to integrate with a No ...