Search code examples
javascriptjqueryif-statementkineticjs

Drawing new Kinetic JS polygon with click function


I'm trying to trigger the creation of a new Kinetic shape (not a clone) through the click of another. Any help would be greatly appreciated as I can't seem to find an answer. I've tried the following without any luck:

var sq1 = new Kinetic.Rect({
    x: 25,
    y: 400,
    width: 200,
    height: 200,
    fill: '#000000',
    draggable: true
    });

var $sq1 = sq1

$sq1.on( "click", function() {
  var sq1copy = new Kinetic.Rect({
    x: 45,
    y: 450,
    width: 100,
    height: 100,
    fill: '#FFFFFF',
    draggable: true
    });
});

Solution

  • You've almost got it...just be sure to add the new sq1 to the layer and also layer.draw

        var stage = new Kinetic.Stage({
            container: 'container',
            width: 750,
            height: 750
        });
        var layer = new Kinetic.Layer();
        stage.add(layer);
    
    var sq1 = new Kinetic.Rect({
        x: 25,
        y: 100,
        width: 200,
        height: 200,
        fill: '#000000',
        draggable: true
    });
    layer.add(sq1);
    layer.draw();
    
    var $sq1 = sq1
    var offset=20;
    
    $sq1.on( "click", function() {
      var sq1copy = new Kinetic.Rect({
        x: 45+offset,
        y: 150+offset,
        width: 100,
        height: 100,
        fill: '#FFFFFF',
        draggable: true
        });
        offset+=20;
        layer.add(sq1copy);
        layer.draw();
    });
    body {
      padding: 20px;
    }
    #container {
      border: solid 1px #ccc;
      margin-top: 10px;
      width: 750px;
      height: 750px;
    }
    <script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v5.1.0.min.js"></script>
    <div id="container"></div>