How do I use vtkjs to color cells individually

Assign a field to your cells and color by that field.

I can understand what you mean, but I’m sorry that I don’t quite understand how to write this code. Could you please give me a similar example?

I tried to do this using the filter Calculator, but if I did this, the other cells wouldn’t stay white and would turn red, as shown in the image below.

I had to color cells individually once before, and here is the approach I took:

  addScalarsForColor = vtkCalculator.newInstance();
  addScalarsForColor.setInputConnection(<the previous filter whose output is polydata>.getOutputPort());
  addScalarsForColor.setFormula({
    getArrays: inputDataSets => ({
      input: [],
      output: [
        { location: FieldDataTypes.CELL, name: 'MyColorsArray', dataType: 'Int8Array', attribute: AttributeTypes.SCALARS, numberOfComponents: 3 },
      ],
    }),
    evaluate: (arraysIn, arraysOut) => {
      let dataArray = arraysOut[0]; // a vtkDataArray
      for (let i = 0; i < dataArray.getNumberOfTuples(); i++) {
        dataArray.setTuple(i, <set the color of the i^th cell here (an RGB vector like [255,255,182])> );
      }
    },
  });


  mapper = vtkMapper.newInstance();
  mapper.setInputConnection(addScalarsForColor.getOutputPort());
  mapper.setScalarVisibility(true); // it's true by default but, but just emphasizing here that we need it to be.
  mapper.setScalarModeToUseCellFieldData(); // use cell field data to set colors; this necessitates the next line
  mapper.setColorByArrayName('MyColorsArray'); // since we use cell field data for colors, we need to specify which data array will be used

  // this makes it so that the cell field data array that we use for colors is interpreted directly as RGB values, rather than as scalars to be passed through some lookup table.
  mapper.setColorModeToDirectScalars();
2 Likes

Excellent. That’s very useful. Thank you very much for your answer.

1 Like