2
votes

I've got this calling function

    $(document).ready(function(){
       $('#change-background').click(function(){
         layers['map'] = new Kinetic.Layer();
         buildMap(layers['map'],'img/test.png');
         stage.add(layers['map']);
       });
    });

And, I've got this function to display the image

    function buildMap(layer, img_src){
      var img = new Image();
      img.src = img_src;
      img.onload = function(e) {
        var map = new Kinetic.Image({
          id: 'map_img',
          x: 0,
          y: 0,
          image: img,
          draggable: true,
          dragBoundFunc: function(pos) {
            // THIS SHOULD EXECUTE
            console.log('hahaha');
            return { x:0, y:0 };
          }
        });
        layer.add(map);
        layer.draw();
      };
    }

I have a similar code on a separate project of mine, and it works like a charm.. But its quite awkward that it does not work well here. The image showed up in the canvas, and its draggable, which in this case it should not be because I explicitly returned { x:0, y:0 }(the return values is for my testing only). I also looked at the console logs the 'hahaha' text never appears.. It did not call the function when the image has been dragged. Both of these are inside a <script> tags and in one html document.

1
I just saw the error causing the problem.. I've been using kinetic-v3.10.0 for this project.. I think this version 3.10.0 have some issues with the dragBoundFunc.. I tried importing the 4.2.0 but error will display on my console..Dhagz
jsfiddle link: linkDhagz
have you considered using a newer version of kineticjs? like 4.3?SoluableNonagon
i have just tried it.. and yes.. my dragBoundFunc worked.. but my 'Add New Polygon' doesn't.. the console will be me the message Uncaught TypeError: Cannot read property 'x' of undefined and if i'll collapse it there would be a (anonymous function) written.Dhagz

1 Answers

1
votes

Fixed this: http://jsfiddle.net/xpLPT/2/

try :

 dragBoundFunc: function(pos) {
      console.log('hahaha');  //check the jsfiddle, this does work.
      return {
        x: this.getAbsolutePosition().x,  //constrain vertically
        y: this.getAbsolutePosition().y   //constrain horizontally
      }
 }

also change your click function by adding stage.draw();:

$(document).ready(function(){
   $('#change-background').click(function(){
     //if(layers['map'])
          // layers['map'].remove(); // this is optional, but recommended, as it removes the current map layer before adding a new one
     layers['map'] = new Kinetic.Layer();
     buildMap(layers['map'],'img/test.png');
     stage.add(layers['map']);
     stage.draw();
   });
});

try using a newer version of kinetics:

    <script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.3.0.min.js"></script>