What techniques can I use to adjust the size of an image through zooming in and out?

In my custom gallery component, the crucial code section looks like this:

       

     <Gallery>
      <Header>
        <img src={galleryIcon} alt='Galley icon' />
        <h1>My Gallery</h1>
      </Header>
      <Images isImage={custom.length > 0}>
        {custom.length > 0 &&
          custom.map((c, i) => (
            <img
              id={`custom${i}`}
              key={`custom${i}`}
              src={c.img}
              alt='brick'
              onClick={() => (setEdit((prev) => !prev), setActual(c))}
            />
          ))}
        <div className='add'>
          <button onClick={() => setGallery((prev) => !prev)}>
            <img src={add} alt='Add icon' />
          </button>
          <p>Click to add a brick from our collections!</p>
        </div>
      </Images>
    </Gallery>

Each image in the gallery follows this styling:

img {
    box-sizing: border-box;
    height: 28vh;
    width: 28vh;
    margin-right: 1.5rem;
    cursor: pointer;
  }

Furthermore, whenever a user inputs a new image, I implement a resizing mechanism that maintains scale integrity using this function:

export function resizeImage(
  file: File | Blob,
  maxWidth: number,
  maxHeight: number,
  scale = 1
): Promise<Blob> {
 // Function details...
}

Lastly, the Resize component enables users to adjust images with a pinch and zoom feature as part of DOM manipulation:

const Resize: React.FC<Props> = ({ actual, setResize, setCustom, custom }) => {
 // Component details...
};

I am also utilizing the react-zoom-pan-pinch library for enabling zoom functionalities. My concern revolves around dynamically resizing images on the DOM based on zoom scaling triggered by TransformWrapper component's onZoomChange function. Is there a cleaner approach to achieve image resizing in accordance with zoom scale adjustments?

A minimalistic repository will be shared soon, but in the meantime, you can access the complete repo here: https://github.com/Mdsp9070/brickart/tree/dev

Answer №1

Yes, it is indeed achievable, but in order to implement this functionality, you must ensure that you are passing all the required props to drawImage. Make sure to refer to the official documentation for a complete understanding. There are additional optional arguments beyond the first four that you should be utilizing. By incorporating all eight props, you can precisely determine which portion of the original image to crop and then specify its positioning on your canvas.

To achieve this, you will need to perform some calculations involving mathematics as well as track relevant events to determine the source rectangle based on the center of the zoom and the scale factor applied.

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

When testing, Redux form onSubmit returns an empty object for values

Is it possible to pass values to the onSubmit handler in order to test the append function? Currently, it always seems to be an empty object. Test Example: const store = createStore(combineReducers({ form: formReducer })); const setup = (newProps) => ...

"Setting the minimum length for multiple auto-complete suggestions in

How can I dynamically set the minLength of an input field based on whether a numeric value is coming from the "#lookup" field? Is there a way to achieve this using JavaScript and jQuery? <script type="text/javascript"> $(document).ready(function() ...

Creating a Vue.js vuetify input that restricts the user to entering only three digits before the decimal point and two digits after the decimal point

I am looking to implement a restriction on the total number of input digits to 3. Users should be able to enter numbers like 333, 123, etc. However, if they include a decimal point, they should only be allowed to enter 2 digits after the decimal point. Val ...

Achiever.js - Incorporating incremental progress with half stars instead of whole stars

Hello there! I've been utilizing Rater.js in my current project, and so far it has provided me with satisfactory results. However, I have encountered a particular issue that I am struggling to resolve on my own. It would be greatly appreciated if you ...

Applying TPS rate to existing API endpoints at the method level within API Gateway using AWS CDK

I have successfully set up a UsagePlan and connected it to an API stage with CDK. However, I am having difficulty implementing method throttling at the API stage for a specific resource path. Despite searching online, I have not been able to find a satis ...

Error: Unable to locate module: '*.module.scss'

I'm a beginner in React and I encountered an error when trying to use the Grid component in material-ui.com. The error message displayed is "Module not found: Can't resolve '.module.scss'". Does anyone know how to solve this issue? Her ...

In JavaScript, unchecking a radio button results in all options becoming uncheckable

I have a pure CSS accordion and I want to enhance it with some JavaScript functionality for users who have JavaScript enabled. The CSS accordion currently utilizes the :checked pseudo-class. The new feature I am looking to add is: if a button that is alre ...

Using jQuery to manipulate text

Can I modify this code to function within "{}" instead of using the .chord tags? (Jquery) //This code transposes chords in a text based on an array var match; var chords = ['C','C#','D','D#','E',&apo ...

Dynamic React Gallery with Interactive Image Picker

Looking to develop a new photo management application as an alternative to Google Photos, with a focus on displaying and selecting images in a user-friendly way. Currently using the react-grid-gallery library for this purpose. Here is my current implement ...

Switching carousel background image upon navigation click

I am currently working with a Bootstrap Carousel and I want to customize the background (an image) for each slide. I have 4 slides in total, each corresponding to a specific background image. <!DOCTYPE html> <html lang="en" dir="ltr ...

Exploring nested hash maps within JavaScript

Having some trouble with creating a nested hash map in JavaScript (js), similar to the example below: let rooms = {}; rooms[roomNum][personName] = somethings; However, I keep encountering an error when attempting this: TypeError: Cannot set property &apo ...

Eslint highlighting the initial function declaration within a Vue script

I'm currently creating a Vue file using a Typescript script, and encountering an unusual Eslint "error." The issue arises on line 15 with this specific complaint: Parsing error: Unexpected token, expected "," Interestingly, this error only occurs wi ...

What is the best way to include variable child directives within a parent directive in AngularJS?

Exploring a New Angular Challenge In the current project I am engaged in, I am faced with a unique problem that requires an 'angular way' solution. Despite my best efforts, I seem to be hitting a roadblock every time I attempt to solve it. The ...

Utilizing Next.js to Import a Function from a Path Stored within an Environment Variable

I'm having trouble importing a function whose path is stored in an environment variable Current import statement: import { debug } from '../lib/site-A/utils' Expected import statement: import { debug } from process.env.DEBUG_PATH In my ...

Method for transmitting JSON array from Controller to View using CodeIgniter

I have a function in my controller: function retrieveAllExpenses() { $date=$this->frenchToEnglish_date($this->input->post('date')); $id_user=$this->session->userdata('id_user'); $where=array('date&ap ...

"Exploring the seamless integration of Next.js and Material UI for stunning web

I have encountered an issue while using Next.js and Material-UI(@mui/core) to build a website. Everything works perfectly when I run it with next dev, but the styles get messed up when using next build && next start. In addition to Material-UI, I ...

Pagination problem arises when sorting through items

I am facing an issue with filtering items on different pages of my React website. The problem I encounter is that the filtering functionality only works on the initial page where the data is loaded. Code: CustomersEpolicyPage.tsx import React, {useEffect ...

What is the best way to eliminate all borders from a select box?

Is there a way to completely remove all borders from the selectbox using either CSS or JQuery? The code snippet is as follows: <select id="doctor_ch"> <option value="1" selected>One</option> <option value="2">Two</option& ...

State information is not successfully transferred to props during a GET request

I'm in the process of creating a blog with NextJs and Prismic CMS. When the page loads, data is shown by passing information from <Blog /> to <cards-list ?> and then to <Card />. Upon clicking the loadmore button, it triggers a requ ...

ng-enter animation not working for ui-view nested within another ui-view after page reload

It seems like the issue lies with the ng-enter event not being properly triggered in the lowest level of the ui view hierarchy. I'm unsure how to resolve this problem effectively. In my extensive angularjs application, nested sub-views work flawlessl ...