5

I have a canvas which will hold a moderate to large amount of shapes (50-500).

I have succeeded in drawing the outline of the shape I would like using these tools:

function DrawPolygon(diagramLayer, polygon) {
    var diagramImage = new Kinetic.Shape(function () {
        var context = this.getContext();
        context.beginPath();
        context.lineWidth = 1;
        context.strokeStyle = "#ff0000";

        var lastVertice = polygon.Vertices[polygon.Vertices.length - 1];

        context.moveTo(lastVertice.X, lastVertice.Y);

        for (var i = 0; i < polygon.Vertices.length; i++) {
            var vertice = polygon.Vertices[i];
            context.lineTo(vertice.X, vertice.Y);
        }

        context.stroke();
        context.closePath();
    });

    diagramImage.on("mouseover", function () {
    });

    diagramLayer.add(diagramImage);
    planViewStage.add(diagramLayer);
}

I would like to change diagramImage's context's strokeStyle to a different color on mouseOver. I understand that the canvas element does not keep track of 'state' and, as such, has no idea that there is a shape on it currently.

I am wondering a few things:

  1. Does the above fact about Canvas hold true for Kinetic's layer element?
  2. It seems like I would need to clear diagramImage's context and redraw using a different color -- will this cause flicker on mouseover?
  3. Would drawing another color of shape 'underneath' my current shape be beneficial at all? Can I then hide the shape on top -- perhaps by modifying a z-index -- to seemingly 'change' the color of the shapes?
  4. If 3 is true, would this have any performance concerns with doubling 500 elements to 1000?
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Sean Anderson
  • 27,963
  • 30
  • 126
  • 237

1 Answers1

8

Here's a lab that shows how you can change a shape's color with mouseover:

http://www.html5canvastutorials.com/labs/html5-canvas-interactive-flower/

Eric Rowell
  • 5,191
  • 23
  • 22
  • Just to let you know, this is very helpful. A good question and a good answer. Exactly what i was looking for. – Joe Slater Mar 21 '13 at 19:03
  • How can I add the same behaviour but for selected shape with the mouse click and persist the color until I select a different shape? Is there a property like "IsSelected"? Thank you – Cornel Urian Aug 08 '13 at 07:56
  • cornel - lots of ways to do that. You can set custom shapes like shape.setAttr('selected', true); if you wanted. Or you could just check the shape color to determine if its selected with shape.getFill() – Eric Rowell Aug 23 '13 at 00:05