Search code examples
javascriptcssreactjscropjcrop

Problem with image centering while cropping


I have a simple component with single image cropping. But I have problem with proper centering the cropped image.

Look at my working code: https://codesandbox.io/s/sharp-mayer-b371f?from-embed

You will see that image cropping works very nicely, cropped images appear below parent image.

However, you will also notice that the cropped image is not correctly centered, sometimes it is moved too right, sometimes too left and so on.

You will also see that the height and width of cropped image aswell as the marked area on parent image are the same. Still tough some little part is missing.

Looking for help, thank you!

P.S. Couldnt drop code in stack overflow snippets, since its too complicated and relies on npm package called 'Jcrop'. To test it, simply click on parent image and move cursor.

enter image description here


Solution

  • Your image is shifted because you're using background-position-x: ((x / width) * 100) % (and similar for y) for displaying the cropped image, which is wrong.

    For shifting background n pixels, you can't use percentages (here is why: https://stackoverflow.com/a/47329797/4718434). instead you can use:

    background-position: -x px
    

    So change your react code to:

    const marginLeft = - pos.x + "px";
    const marginTop = - pos.y + "px";
    

    Sandbox: link