Search code examples
canvashtml5-canvaskonvajsreact-konvakonva

How to make image stays inside the canvas and make sure the white space is not showing up : Konva.js while zoomed in and moving


I need your help since I am struggling with this. I have implemented zoom in and user should be able to move around by clicking the button. I can't use draggable in Stage because of my situation. User must click right button to move right and left to move left. But, the thing is, I am seeing the white huge white space and I am not sure how to do the calculation to prevent it. At least, I am able to prevent it for the Y axis when moving top just like this

// For moving up

      setStageY((pre) => (pre + 50 > 0 ? 0 : pre + 50));

Here if adding 50 to previous Y coordinate is greater than 0, just returning 0 does the trick. But, I am not sure how to handle for the moving down part. Can someone help me with this please??

Here is the demo

https://codesandbox.io/s/react-konva-draw-polygon-forked-uhhz0c

My Requirement I must be able to zoom in and move around while image remains within the border. No white space should appear.


Solution

  • Let's look at some numbers to give you a better understanding. Let's say your stage's height is 300 pixel, the image's height is 300 pixel too but the scale is set to 1.5. This means the actual height of the image is 450 pixel (300*1.5).

    If we take a look at the following graphic

    we can see that the image should be drawn at y=-150 to stay in the borders of the stage. If we look at the numbers to the right, we figure it's simply the difference between the stage and the image's height.

    So all you have to do is:

    <button onClick={() => {
              setStageY((prev) => (prev - 40 > 300 - 300 * scale ? prev - 40 : 300 - 300 * scale));
    }}> Bottom </button>