Sinan Samet
Sinan Samet

Reputation: 6752

Drag and drop inside an image with kineticjs

I want to drop the star on a tree and detect which tree the star has been dropped on so I can highlight and select it eventually. But I couldn't get more than just moving the star.

I chose for kineticjs because it works with touchscreen so I don't want to use something else if possible. (unless it works with both touchscreen and mouse too)

This is my javascript:

<script defer="defer">
  function drawImage(imageObj) { 
    var stage = new Kinetic.Stage({
      container: "star",
      width: 900,
      height: 500
    });
    var layer = new Kinetic.Layer();

    // star
    var star = new Kinetic.Image({
      image: imageObj,
      x: 376,
      y: 30,
      width: 40,
      height: 46,
      draggable: true,
      draw: false
    });

    // add cursor styling
    star.on('mouseover', function() {
      document.body.style.cursor = 'pointer';
    });
    star.on('mouseout', function() {
      document.body.style.cursor = 'default';
    });

    layer.add(star);
    stage.add(layer);
  }
  var imageObj = new Image();
  imageObj.onload = function() {
    drawImage(this);
  };
  imageObj.src = 'http://upload.wikimedia.org/wikipedia/commons/d/df/Star_icon_1.png';

</script>

Please see the fiddle for the full code: http://jsfiddle.net/hpq7rpnh/1/

Upvotes: 0

Views: 118

Answers (1)

SoluableNonagon
SoluableNonagon

Reputation: 11755

Add the trees as their own objects, and then you can check collision between stars and trees:

var starLayer = new Kinetic.Layer(); // its own layer, index should be above tree layer
var treeLayer = new Kinetic.Layer(); // its own layer

stage.add(treeLayer);
stage.add(starLayer);

var tree = new Kinetic.Rectangle( ... );

treeLayer.add(tree); 

var tree2 = new Kinetic.Rectangle( ... ); // another tree at another coordinate
treeLayer.add(tree2); // assuming you have a layer for Trees ONLY already

later on, when the user drops the star, you need to check collision

// sample bounding box collision detection
function checkCollision(){
    var trees = treeLayer.getChildren(); // gets all the trees
    for(tree in trees)
        if(star.xCoord > tree.xCoord && star.xCoord + star.width < tree.xCoord + tree.width ... same for y coordinates)
}

Upvotes: 1

Related Questions