What is the best way to implement changes in position from react-easy-crop to update a live image displayed in a separate div on the webpage?

Once an image is selected, it is displayed in two different places: one within react-easy-crop with a 4:3 aspect ratio, and the other in a separate div sized at 960w*510h. When the crop position is changed in react-easy-crop, the position of the image in the separate div should also move accordingly. This involves listening to the onchangecrop event from react-easy-crop.

onCropChange = (crop) => {
    //crop contains x and y translated values in pixels
    pageObj = `${crop.x * -1}% ${crop.y * -1}%`.toLowerCase();
    //pageObj now holds the x and y positions in percentage.
}

Answer №1

If you're looking to showcase a preview image, consider utilizing a canvas element for editing the original image by cropping and repositioning it.

import React, { Component } from 'react';
import { render } from 'react-dom';
import Cropper from 'react-easy-crop'

export class App extends Component {
  canvas = {}

  state = {
    image: 'https://www.gravatar.com/avatar/3d721f4c46282afc254f3ea0cd05df30?s=170&d=identicon&r=PG',
    crop: { x: 0, y: 0 },
    zoom: 1,
    aspect: 4 / 3,
    croppedAreaPixels: {}
  }

  onCropChange = crop => {
    this.setState({ crop })
  }

  onCropComplete = (croppedArea, croppedAreaPixels) => {
    console.log(croppedArea, croppedAreaPixels);
    const ctx = this.canvas.getContext('2d');
    const image = document.getElementById('source');

    this.canvas.setAttribute('width', croppedAreaPixels.width);
    this.canvas.setAttribute('height', croppedAreaPixels.height);
    ctx.drawImage(image, croppedAreaPixels.x, croppedAreaPixels.y, croppedAreaPixels.width, croppedAreaPixels.height, 0, 0, croppedAreaPixels.width, croppedAreaPixels.height);
    this.setState({
      croppedAreaPixels 
    })
  }

  onZoomChange = zoom => {
    this.setState({ zoom })
  }

  render() {
    const { image, croppedAreaPixels, crop, zoom, aspect } = this.state;
    return (
      <>
        <img id="source" style={{display: 'none'}} src={image} />
        <canvas ref={canvas => this.canvas = canvas} width={croppedAreaPixels.width} height={croppedAreaPixels.height}></canvas>
        <Cropper
          image={image}
          crop={crop}
          zoom={zoom}
          aspect={aspect}
          onCropChange={this.onCropChange}
          onCropComplete={this.onCropComplete}
          onZoomChange={this.onZoomChange}
        />
      </>
    )
  }
}

render(<App />, document.getElementById('root'));

For a demonstration of this in action, check out this link:

https://stackblitz.com/edit/react-easy-crop-with-preview

Alternatively, explore the use of background-position as another method instead of relying solely on the canvas.

https://stackblitz.com/edit/react-easy-crop-with-preview-with-bg-position

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

Accurate understanding of URL parameters and hashtags

Imagine an HTML document containing two blocks, where the content of only one block can be displayed at a time by toggling between them using menu buttons and/or URL parameters with the same JavaScript functions provided below: <div class="block1&q ...

Prevent anchor link click and drag functionality on an HTML page / Swipe through a container containing links

Is there a way to prevent clicking and dragging on a link in a webpage? When you click the left mouse button on a link and drag it, you can unintentionally move the link or open a new tab. I am looking for a way to disable this behavior using JavaScript o ...

Adding video files and subtitle files to our MongoDB database

// backend/server.ts import express, { Application, Request, Response } from 'express'; import mongoose from 'mongoose'; import cors from 'cors'; import dotenv from 'dotenv'; const multer = require('multer&apos ...

What is the method for determining the overall page load time of a website, taking into account the total loading time instead of just the document.ready()

I recently attempted to create a function using either JavaScript or Python with Selenium to measure the page load time of a website. While document.ready() gives me the DOM load time, it may not capture AJAX calls that occur afterwards. I noticed there i ...

What level of security can be expected from this particular JavaScript code when executed on a server environment like nodeJS?

Wondering about potential challenges that may arise when running this code on the server, as well as any alternatives to using eval. var obj = {key1: 'value1', key2: 'value2', key3: 'value3', key4: ['a', 'b&apo ...

Transfer content within <pre> tags to the clipboard using a Vue.js application

I am currently developing a Chrome extension using Vue.js where I aim to copy the content within a pre tag section to the clipboard with the click of a button. By assigning an element ID to the pre tag, I can retrieve the content using a copyToClipboard() ...

Try using inline styling to configure the opening direction of the Select tag in a React application

I have scoured the internet searching for a solution to this issue, and the only advice I seem to find with the most upvotes on every website is either: menuContainerStyle={{top: 'auto', bottom: '100%'}} as an inline solution or som ...

Use jQuery to display the user input value in real-time

I am in the process of developing a dynamic calculation program to sharpen my jQuery skills, but unfortunately, I'm facing some challenges. I have managed to store values in variables as shown in the code snippet below. <form> Table of: ...

Automatically populate a jQuery dropdown box with MySQL data

I have a scenario where I need to create 2 dropdown boxes. The first dropdown box will display all the tables from a database, and when a table is selected, the second dropdown box should be populated with fields from that specific table. Dropdown Box 1: ...

What steps can be taken to stop clients from sending an OPTION request prior to each GET?

Is there a way to deactivate the behavior of the client performing an OPTIONS request before every GET request? ...

"Revolutionary jQuery plugin designed to function independently of HTML elements

Is it possible to create a jQuery plugin that can be executed without the use of an element selector? Typically, we use: $('#myElementID').myPluginFunction(myVariables); But, is there a way to do it like this instead? $.myPluginFunction(my ...

An Overview of Node.js Application Structure

Guten Tag! My name is Alex, and I am from Germany. I apologize for any mistakes in my English as it is not my first language. I have recently started learning programming with Node.js after creating some simple static HTML and CSS websites. As a beginner, ...

Problem encountered while attempting to deploy a project using both Express.js and React.js on Heroku

My website is working perfectly locally, but I encounter an error when trying to deploy it on Heroku. Here's some background information: The back-end server was built following this tutorial (Express.js + Sequelize + PostgreSQL): The front-en ...

Using AJAX in Rails to dynamically display information in a div on the webpage

In my project, I have a model named Area and what I want to achieve in the index page is loading the area_path(area) within a div element instead of redirecting users to another page. Here are the code snippets that I have implemented so far: <h3>W ...

Using angular.js variables in the script tag: A step-by-step guide

Currently, I am working on a project that involves displaying elements on a view using Angular.js and attempting to connect these DOM elements using jQuery connections. While the elements are being displayed correctly, I am encountering an issue when tryin ...

Hiding the filelist on antd-Upload when the URL is not provided

When passing a Url as a prop to display uploaded files in an edit Modal, I want to ensure that no attachments are shown if the Url is empty. Currently, I am still seeing empty attachments displayed as shown in the image: https://i.sstatic.net/dkzu1.png ex ...

How to trigger a JavaScript function using a link in CakePHP?

When working with Html, <a href="some_url"> Contact Seller </a> In the realm of Cakephp, <?php echo $this->Html->link('Contact Seller', array('controller'=>'pages', 'action'=>'conta ...

The playwright and Vite testing block is unable to locate a specific element, despite its presence

Currently, I am conducting e2e tests utilizing playwright in conjunction with a vite frontend application. Below is the code snippet: import { test, expect } from '@playwright/test'; test.describe('Auth page @auth-page', () => { ...

ID is Enclosed in Quotation Marks by JSON.Stringify

My JSON file is being modified by using JSON.stringify and JSON.parse based on updates from an online database. While everything is functioning correctly, there is an issue where numbers are being converted to strings with quotes in the JSON file. For in ...

Using AJAX to send data with a POST request in Django may not function properly

Let me preface by saying I have searched for solutions online, but none of them seem to address my specific issue (mainly because they use outdated methods like Jason). I am currently working on a Django project and trying to implement ajax for a particul ...