mosnoi ion
mosnoi ion

Reputation: 133

how to crop same image multiple times with konva.image

i am trying to get cells from a photo with a table. i have the coordonates of the cells in the image. now i want to view my cells using a konvajs library. the problem is that the table is 30x30. so i have 900 cells. when using kanva.image 900 times the browser stop working, because it tries to load 900 time the same image. i want to load one time the image and use it for croping 900 time. here are my code:

function add_i(layer,cell,row,weight,k,cloneI){         

        layer.add(cloneI);

        cloneI.crop({
              x: parseInt(cell.x),
              y: parseInt(row.y),
              width: cell.width,
              height: row.height
            });
            cloneI.width(cell.width);
            cloneI.height(row.height);
            cloneI.y(row.y);
            cloneI.x(cell.x);

    }
    layerP.push( new Konva.Layer());
    if(weight.stage == 'pred'){
      var cloneI = new Konva.Image({
            id:'img_'+k,
            draggable: true
      });
      var clone = new Image();

      clone.onload = function() {
            cloneI.image(clone);               

            layerP[0].draw();
      };


      for (var i in weight.predictions){
        var row = weight.predictions[i];
        for (var j in row.cells){
          var cell = row.cells[j];  
          add_i(layerP[0],cell,row,weight,k,cloneI.clone());              

          k+=1;
        }
        if(i==4 && false)
          break;
      }
      clone.src = weight.path_i;
      stage.add(layerP[0]); 
    }

Upvotes: 0

Views: 1113

Answers (1)

Hitesh Kumar
Hitesh Kumar

Reputation: 3698

I think you should move your add_i into clone.onload like this:

function add_i(layer, cell, row, weight, k, cloneI) {

  layer.add(cloneI);

  cloneI.crop({
    x: parseInt(cell.x),
    y: parseInt(row.y),
    width: cell.width,
    height: row.height
  });
  cloneI.width(cell.width);
  cloneI.height(row.height);
  cloneI.y(row.y);
  cloneI.x(cell.x);

}
layerP.push(new Konva.Layer());
if (weight.stage == 'pred') {
  var clone = new Image();

  clone.onload = function() {
    var cloneI = new Konva.Image({
      id: 'img_' + k,
      draggable: true,
      image: clone
    });

    for (var i in weight.predictions) {
      var row = weight.predictions[i];
      for (var j in row.cells) {
        var cell = row.cells[j];
        add_i(layerP[0], cell, row, weight, k, cloneI.clone());

        k += 1;
      }
      if (i == 4 && false)
        break;
    }
    layerP[0].draw();
  };
  clone.src = weight.path_i;
  stage.add(layerP[0]);
}

cause the add_i is invoked before the onload callback because of that Konva.Image i.e. cloneI does not have native image instance when it's used.

Upvotes: 2

Related Questions