pbond
pbond

Reputation: 1927

Previous shape dissappears after adding new one - KineticJS

I have my document.ready function in which I create several layers, including my linesLayer, like this (and my stage):

var pointsLayer = new Kinetic.Layer();
var linesLayer = new Kinetic.Layer();
var stage = new Kinetic.Stage("container", 578, 325);

In my document.ready function I have a click function for my canvas, herein I create a new circle for example (which represents a point/dot on the screen) like this:

var circle = new Kinetic.Circle({
    name: "x"+x+"y"+y,
    x: x,
    y: y,
    radius: 5,
    fill: "red",
    stroke: "black",
    strokeWidth: 1
});

After that I create my line:

var line = new Kinetic.Shape({
    drawFunc: function(){
        var context = this.getContext();
        context.beginPath();
        context.lineWidth = 1;
        context.strokeStyle = "black";
        context.fillStyle = "red";
        context.moveTo(startPoint.x, startPoint.y);
        context.lineTo(endPoint.x, endPoint.y);
        context.closePath();
        context.fill();
        context.stroke();
    }
});

And then I add them to their respective layers:

linesLayer.add(line);
pointsLayer.add(circle);

And add them to the stage:

stage.add(pointsLayer);
stage.add(linesLayer);

Now what happens is, when I draw my dots/circles, they all stay on the screen, like I want them to be. So if I click 10 times, I have 10 dots. Now the problem is, this DOES draw a line, but it only draws 1 line everytime, the latest line between two dots, instead of that it leaves all the previous lines on the screen. Why is this happening, since I'm adding them to the layer, and not doing anything with the previous lines in the lineslayer?

So basically, it does add my circles to the pointslayer like I want them, and leaves the previous added elements untouched, but whenever I add a line to the lineslayer, all previous elements of the lineslayer dissapear?

Edit: Fixed it with this code, unsure why this does work though.

            // Create line
            var line = new Kinetic.Shape({
                drawFunc: function(){
                    var context = this.getContext();
                    context.beginPath();
                    context.moveTo(prevPoint.x, prevPoint.y);
                    context.lineTo(x, y);
                    context.closePath();
                    this.fillStroke();
                },
                stroke: "orange",
                name: "x"+x+"y"+y+"nr"+nr_coords,
                strokeWidth: 2
            });

Upvotes: 0

Views: 973

Answers (1)

Eric Rowell
Eric Rowell

Reputation: 5219

Well for one thing you're using different variables between your first post and your second post. In your first post, you're using startPoint and endPoint objects. In the second post you're using a prevPoint object. I'm guess the problem was related to however those variables were being set (code not shown)

Upvotes: 2

Related Questions