Recoloring a shape on mouseover using KineticJS

2019-04-29 14:30发布

问题:

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?

回答1:

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/