'Drag and Drop limitation in Konva js

I recently began to learn Konva-JS... please help me :)

<script>
    var width = window.innerWidth;
    var height = window.innerHeight;
    function loadImages(sources, callback) {
        var assetDir = '/assets/';
        var images = {};
        var loadedImages = 0;
        var numImages = 0;
        for(var src in sources) {
            numImages++;
        }
        for(var src in sources) {
            images[src] = new Image();
            images[src].onload = function() {
                if(++loadedImages >= numImages) {
                    callback(images);
                }
            };
            images[src].src = assetDir + sources[src];
        }
    }
    function isNearOutline(animal, outline) {
        var a = animal;
        var o = outline;
        var ax = a.getX();
        var ay = a.getY();
        if(ax > o.x - 20 && ax < o.x + 20 && ay > o.y - 20 && ay < o.y + 20) {
            return true;
        }
        else {
            return false;
        }
    }
    function drawBackground(background, beachImg, text) {
        var context = background.getContext();
        context.drawImage(beachImg, 0, 0);
        context.setAttr('font', '20pt Calibri');
        context.setAttr('textAlign', 'center');
        context.setAttr('fillStyle', 'white');
        context.fillText(text, background.getStage().getWidth() / 2, 40);
    }
    function initStage(images) {
        var stage = new Konva.Stage({
            container: 'container',
            width: 578,
            height: 530
        });
        var background = new Konva.Layer();
        var animalLayer = new Konva.Layer();
        var animalShapes = [];
        var score = 0;
        // image positions
        var animals = {
            snake: {
                x: 10,
                y: 70
            },
            giraffe: {
                x: 90,
                y: 70
            },
            monkey: {
                x: 275,
                y: 70
            },
            lion: {
                x: 400,
                y: 70
            }
        };
        var outlines = {
            snake_black: {
                x: 275,
                y: 350
            },
            giraffe_black: {
                x: 390,
                y: 250
            },
            monkey_black: {
                x: 300,
                y: 420
            },
            lion_black: {
                x: 100,
                y: 390
            }
        };
        // create draggable animals
        for(var key in animals) {
            // anonymous function to induce scope
            (function() {
                var privKey = key;
                var anim = animals[key];
                var animal = new Konva.Image({
                    image: images[key],
                    x: anim.x,
                    y: anim.y,
                    draggable: true
                });
                animal.on('dragstart', function() {
                    this.moveToTop();
                    animalLayer.draw();
                });
                /*
                       * check if animal is in the right spot and
                       * snap into place if it is
                       */
                animal.on('dragend', function() {
                    var outline = outlines[privKey + '_black'];
                    if(!animal.inRightPlace && isNearOutline(animal, outline)) {
                        animal.position({
                            x : outline.x,
                            y : outline.y
                        });
                        animalLayer.draw();
                        animal.inRightPlace = true;
                        if(++score >= 4) {
                            var text = 'You win! Enjoy your booty!';
                            drawBackground(background, images.beach, text);
                        }
                        // disable drag and drop
                        setTimeout(function() {
                            animal.draggable(false);
                        }, 50);
                    }
                });
                // make animal glow on mouseover
                animal.on('mouseover', function() {
                    animal.image(images[privKey + '_glow']);
                    animalLayer.draw();
                    document.body.style.cursor = 'pointer';
                });
                // return animal on mouseout
                animal.on('mouseout', function() {
                    animal.image(images[privKey]);
                    animalLayer.draw();
                    document.body.style.cursor = 'default';
                });
                animal.on('dragmove', function() {
                    document.body.style.cursor = 'pointer';
                });
                animalLayer.add(animal);
                animalShapes.push(animal);
            })();
        }
        // create animal outlines
        for(var key in outlines) {
            // anonymous function to induce scope
            (function() {
                var imageObj = images[key];
                var out = outlines[key];
                var outline = new Konva.Image({
                    image: imageObj,
                    x: out.x,
                    y: out.y
                });
                animalLayer.add(outline);
            })();
        }
        stage.add(background);
        stage.add(animalLayer);
        drawBackground(background, images.beach, 'Ahoy! Put the animals on the beach!');
    }
    var sources = {
        beach: 'beach.png',
        snake: 'snake.png',
        snake_glow: 'snake-glow.png',
        snake_black: 'snake-black.png',
        lion: 'lion.png',
        lion_glow: 'lion-glow.png',
        lion_black: 'lion-black.png',
        monkey: 'monkey.png',
        monkey_glow: 'monkey-glow.png',
        monkey_black: 'monkey-black.png',
        giraffe: 'giraffe.png',
        giraffe_glow: 'giraffe-glow.png',
        giraffe_black: 'giraffe-black.png'
    };
    loadImages(sources, initStage);
  </script>

as we can see in this example Animals_on_the_Beach_Game the animal's images are drag-able and can be drop ever where.... but I want to change it in the way that it just can drop on the specific place ... what can I do ? thank you :)



Solution 1:[1]

This is more of a design question, as letting go of the mouse button isn't something you can prevent. It would also be non-intuitive to keep the image attached to the mouse position as you would then need a new mouse event to associate with dropping it. What I've done for a drag and drop UI was to either (1) destroy the dropped shape, or if that wasn't an option, (2) animate the shape back (i.e. snap back) to its original position. Alternatively, you might (3) find the closest likely valid drop target and snap to that location.

Solution 2:[2]

First you define lionOrigin, that maybe you already have.

You have to implement the call on the dragend event of the object dragged, so let's say the lion. You have to check position of the lion in relation to the end desired position, let's call it lionDestiny. That can be done with a simple grometry: calculate the distance between to point. We do that with distanceA2B() function.

Now you can establish an offset inside wich you can snap the object, as it is close enough. If the minimal offset is not achieved, then you place the lion back on lionOrigin.

Al last, in konvajs you can use .x() and .y() to easily get or set position to lion.

Something like this:

var lionOrigin = [50,50];
var lionDestiny = [200,200];
var offset = 20;

distanceA2B(a,b) {
  return Math.sqrt( ((a[0]-b[0])*(a[0]-b[0])) + ((a[1]-b[1])*(a[1]-b[1])) );
}

lion.on('dragend', (e) => {
  var d = distanceA2B([lion.x(),lion.y()],lionDestiny);
  if(d<offset){
    lion.x(lionDestiny[0]);
    lion.y(lionDestiny[1]);
  }else{
    lion.x(lionOrigin[0]);
    lion.y(lionOrigin[1]);
  }
});

Hope this helps!

Solution 3:[3]

It would have been better if you could explain your question more when you say you want to move any shape to a specific position. Though konva.js provides you with various events through which you can do this. For example, suppose you want to interchange the location of two shapes when you drag and move the first shape to the second and drop it there. In this case, you can use dragend event of konva. So when you move the target element to another element and drop it there, check if they are intersecting each other or not and then interchange their coordinates with each other.

Here is the function to find the intersection between two elements:

  haveIntersection(r1, r2) {
      return !(
        r2.x > r1.x + r1.width ||
        r2.x + r2.width < r1.x ||
        r2.y > r1.y + r1.height ||
        r2.y + r2.height < r1.y
      );
  }

And from here, you can try to understand the functionality. Though it's in nuxt.js but the events and scripts would be almost same if you are using only javascript. You can find sample code with an explanation for replacing the location of two shapes with each other. So even if you don't want to replace the locations but you want to move your target element to any position this will make you understand how to do this.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Timothy Ryan
Solution 2 Sanxofon
Solution 3