Search code examples
jqueryhtmlcanvasgradientjcanvas

Horizontally Animate Gradient in HTML5 Canvas using jCanvas & jQuery


I want to make the fill gradient of a text inside an HTML5 Canvas element to animate horizontally to create an aurora-like effect by changing the positions of its colorstops (from right to left) dynamically which, I think, can be done using setTimeout() method but I don't know how to do it.

I currently have a static script here:

HTML:

<script src="https://raw.github.com/caleb531/jcanvas/master/jcanvas.min.js"></script>
<canvas></canvas>

Javascript:

var mw = $(document).width();
var mh = $(document).height();

var gs1 = 0
var gs2 = 1/5
var gs3 = 2/5
var gs4 = 3/5
var gs5 = 4/5
var gs6 = 1

$('canvas').attr('width', mw).attr('height', mh);

var Grad = $('canvas').createGradient({
  x1: 0, y1: 0,
  x2: mw, y2: 0,
  c1: '#E33A3A', s1: gs1,
  c2: '#FB57FB', s2: gs2,
  c3: '#21E5EB', s3: gs3,
  c4: '#1ECA18', s4: gs4,
  c5: '#EBD427', s5: gs5,
  c6: '#EB4127', s6: gs6
});

$('canvas').drawText({
  fillStyle: Grad,
  x: mw/2, y: mh/20,
  fontSize: mw/1.8 + '%',
  fromCenter: true,
  fontFamily: "Calibri, Ariel",
  text: 'WOW! Amazing Rainbow!'
})

Please help me, and try to use jCanvas and jQuery syntaxes. Thank you.


Solution

  • var i = setInterval( timer, 500 );
    function timer() {
        if(boo!=='change'){
            boo='change';
            a = '#E33A3A';
            b = '#FB57FB';
            c = '#21E5EB';
            d = '#1ECA18';
            e = '#EBD427';
            f = '#EB4127';
        } else {
            boo='other';
            a = '#EB4127';
            b = '#EBD427';
            c = '#1ECA18';
            d = '#21E5EB';
            e = '#FB57FB';
            f = '#E33A3A';
        }
        console.log( boo );
        dragTextAnimatable();
    }
    

    JSFIDDLE


    NATIVE JAVASCRIPT

    JSFIDDLE

    var gradient = context.createLinearGradient( 0,0,mw,0);
            for (var i=0; i < colorStops.length; i++) {
                var tempColorStop = colorStops[i];
                var tempColor = tempColorStop.color;
                var tempStopPercent = tempColorStop.stopPercent;
                gradient.addColorStop(tempStopPercent,tempColor);
                tempStopPercent += .015;
                if (tempStopPercent > 1) {
                    tempStopPercent = 0;
                }
                tempColorStop.stopPercent = tempStopPercent;;
                colorStops[i] = tempColorStop;
            }