Question

I have a group into layer in Kineticjs with 4 circles as Anchor to resize the image. When click in a button create the image,group and anchors. The issue is when image and circles created the circles seems ok the image doesn't show until click over the area between four circles.

  var userGroup = new Kinetic.Group({
    x: 0,
    y: 0,
    width: width,
    height: height,
    draggable: true
  });

  var layer = new Kinetic.Layer();

  var imageObj = new Image();

  var userImg = new Kinetic.Image({
    id : 'userimg',
    x: 0,
    y: 0,
    image: imageObj,
    width: width,
    height: height,
    name: 'image'
  });

  userGroup.add(userImg);
  layer.add(userGroup);
  stage.add(layer);

  addAnchor(userGroup, 0, 0, 'topLeft');
  addAnchor(userGroup, width, 0, 'topRight');
  addAnchor(userGroup, width, height, 'bottomRight');
  addAnchor(userGroup, 0, height, 'bottomLeft');
  layer.draw();

  userGroup.on('dragstart', function() {
    layer.moveToTop();
    layer.draw();
  });    

  layer.draw();
  imageObj.src = uploadimg; // uploadimg = image url in my root web folder /images
  layer.draw();
  stage.draw();
});  
Was it helpful?

Solution

What happens is your image isn't loaded yet. You are assigning it to a Kinetic.image and updating the layer before the image is even loaded. Therefore you need to add a callback to the onload function of the image.

You should do something like this:

imageObj = new Image();
imageObj.onload = function() {
    var userImg = new Kinetic.Image({
        id : 'userimg',
        x: 0,
        y: 0,
        image: imageObj,
        width: width,
        height: height,
        name: 'image'
    });
    userGroup.add(userImg);
    layer.draw();
};
imageObj.src = uploadimg;

A good practice is load all images you need for your canvas before you even draw something on it. This snippet comes from html5canvastutorials:

function loadImages(sources, callback) {
    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 = sources[src];
    }
}

Usage:

var sources = {
    darthVader: 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg',
    yoda: 'http://www.html5canvastutorials.com/demos/assets/yoda.jpg'
};
loadImages(sources, function(images) {
    //all images are loaded in this callback function
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top