Search code examples
javascriptkineticjsopacity

KineticJS shape opacity


I need some assistance changing the opacity of a shape using KineticJS (5.0.0.). In an mouse event, I want to change the opacity of the shape, which triggered the event. Whenever the shape is hovered, it gets visible ( opacity 1.0 ) and when it's left, it becomes invisible ( opacity 0.0 ). It works fine, whenever I redraw the whole Layer of the specified shape.

The point is, I can't redraw the whole Layer because it takes to much time ( ~300 shapes ). For that reason I changed some code, to just draw the shape.

jsFiddle: http://jsfiddle.net/p39uH/2/ ( see lines 25 and 30 of HTML )

var stage = new Kinetic.Stage({ container: 'container', width: 578, height: 200 }); var layer = new Kinetic.Layer();

  var pentagon = new Kinetic.RegularPolygon({
    x: stage.width()/2,
    y: stage.height()/2,
    sides: 5,
    radius: 70,
    fill: 'red',
    stroke: 'black',
    strokeWidth: 4,
    opacity: 0.1
  });

  pentagon.on('mouseover', function() {
    this.opacity(0.3);
    this.draw(); // instead of layer.draw();
  });

  pentagon.on('mouseout', function() {
    this.opacity(0.0);
    this.draw(); // instead of layer.draw();
  });
  // add the shape to the layer
  layer.add(pentagon);

  // add the layer to the stage
  stage.add(layer);

( Code is based on this: http://www.html5canvastutorials.com/kineticjs/html5-canvas-set-alpha-with-kineticjs/ )

Even though I set the opacity of the shape to 0.0 when left, it's still visible as you can see. Every time it is hovered, it becomes more and more visible ( I guess the shape gets redrawn ).

Is there any way to (re)draw the shape with an opacity of 0.0 WITHOUT drawing the whole stage and/or layer ?

Thanks in advance.


Solution

  • Yes, a quick look indicates node.draw() might be broken in 5.0.1.

    Workarounds:

    • Drop back to version 4.4.0

    • Use layer.drawScene() which saves redraw time by not redrawing the hit-canvas.