Search code examples
html5-canvaseaseljscreatejs

Adding gradient text in createjs


I am currently looking for a way to add a gradient to my text object that was generated with textjs.

    this.text = new createjs.Text(this.val, this.font, "#efa146");
    this.text.textAlign = "center";
    this.text.y = this.pos.y;
    this.text.x = this.pos.x;

    console.log(this.text);

    window.stage.addChild(this.text);

Solution

  • It's actually very easy, just extend the Text object like this

    <script>
        (function () {
            function GradientText(text, font, color) {
                this.Text_constructor(text, font, color);
            }
    
            var p = createjs.extend(GradientText, createjs.Text);
    
            p._drawTextLine = function (ctx, text, y) {
                if (this.gradient) {
                    var height = this.getMeasuredLineHeight();
                    var my_gradient = ctx.createLinearGradient(0, y, 0, y + height);
                    my_gradient.addColorStop(0, "black");
                    my_gradient.addColorStop(1, "white");
    
                    ctx.fillStyle = my_gradient;
                    ctx.fillText(text, 0, y, this.maxWidth || 0xFFFF);
                } else {
                    this.Text__drawTextLine(ctx, text, y);
                }
            };
    
            window.GradientText = createjs.promote(GradientText, "Text");
        }());
    </script>
    

    Now just create an instance of GradientText like this:

     var text = new GradientText("Hello world!", "20px Arial", "#ff0000");
     text.gradient = true;
    

    You should see a gradient over text when you add it to the stage. Here is the jsfiddle for it: https://jsfiddle.net/r94zmwxa/

    P.S. I've just written an example (black and white), but you can change the addColorStop from the this.gradient to set the gradient colors dynamically!