Search code examples
javascriptfabricjs

Fabric js animateColor function not found error


Fabric js animateColor function not found an error. my code for animate text color

var canvas = new fabric.Canvas('mycanvas');
var text = new fabric.Text('text', {
    left: 10,
    top: 12,
    textAlign: 'center',
    fontSize: 15,
        fontFamily: 'Helvetica Nue, Helvetica, Sans-Serif, Arial, Trebuchet MS'
    });

canvas.add(text);
canvas.renderAll();

text.animateColor('#000000','#ffffff',100);
canvas.renderAll();

Solution

  • animateColor is a utility and it is located in the fabric.util namespace. You can read more about it here: http://fabricjs.com/docs/fabric.util.html#.animateColor.

    An example of animating text color using fabric.util.animateColor:

    const ANIMATION_DURATION = 1000;
    const colors = ['red', 'aqua'];
    
    const canvas = new fabric.Canvas('mycanvas');
    const text = new fabric.Text('Animate Color', {
        fill: colors[0],
        fontSize: 35,
        fontWeight: 'bold',
        fontFamily: 'Helvetica Nue'
    });
    
    canvas.add(text);
    
    const swapColors = () => colors.push(colors.shift());
    const toRgba = (val) => Array.isArray(val) 
      ? fabric.Color.fromSource(val).toRgba() 
      : new fabric.Color(val).toRgba();
    const demoColorAnimation = () => {
      fabric.util.animateColor(
        colors[0], 
        colors[1], 
        ANIMATION_DURATION, 
        {
          onChange: (val) => {
            text.setColor(toRgba(val));
    
            canvas.renderAll();
          },
          onComplete: () => {
            swapColors();
            demoColorAnimation();
          }
        }
      );
    };
    
    demoColorAnimation();
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"></script>
    
    <canvas id="mycanvas"></canvas>