vettipayyan
vettipayyan

Reputation: 3308

KineticJS: .SetFill on a polygon updates the fill property but doesn't fill it with color

I have an existing codebase which creates a Stage, and then adds some layers and in one of the layers KineticJS Polygons are drawn. Now I need to update the background of the polygons when user clicks an element that is outside of the stage.

I have managed to get the stage details and then the exact polygon that I wanted to change and also managed to change the fill the polygon with .SetFill method. When I access the polygon's properties, I see the fill property is set correctly. But the background of polygon is not changed.

Is there anything that we need to do after the .SetFill function? Or, what is the proper way to change/update the fill of a KineticJS shape after its creation? I don't see any update or redraw methods...

The code is in Clojurescript, so I don't have exact JS code, but these are the steps that I have:

  1. polygon.setFill(color hexcode)
  2. layer.add(polygon)
  3. stage.add(layer)
  4. stage.draw()

Upvotes: 4

Views: 177

Answers (1)

ctaleck
ctaleck

Reputation: 1665

Here is a kinetic.js example of updating the background of a polygon using the setAttrs method. After the change, the batchDraw method is used to update the layer.

let index = 0;
const colors = [
  [0, 'yellow', 1, 'red'],
  [0, 'red', 1, 'yellow']
];
document.querySelector('#container').addEventListener('click', function() {
  if (index++ > 0) index = 0;
  polygon.setAttrs({
    fillLinearGradientColorStops: colors[index]
  });
  // force update of layer
  layer.batchDraw();
});

const stage = new Kinetic.Stage({
  container: 'container',
  width: 615,
  height: 145
});
const layer = new Kinetic.Layer();
const polygon = new Kinetic.RegularPolygon({
  x: stage.width() / 2,
  y: stage.height() / 2,
  sides: 5,
  radius: 70,
  fillLinearGradientStartPoint: {
    x: -50,
    y: -50
  },
  fillLinearGradientEndPoint: {
    x: 50,
    y: 50
  },
  fillLinearGradientColorStops: colors[index],
  stroke: 'black',
  strokeWidth: 4,
  draggable: true
});
layer.add(polygon);
stage.add(layer);
stage.draw();
<script src="https://cdnjs.cloudflare.com/ajax/libs/kineticjs/5.2.0/kinetic.min.js"></script>
<div id='container'></div>
<div>Click or drag polygon</div>

Upvotes: 1

Related Questions