Awesome html5 canvas animations-part1

Published on by Yousfi Benameur

 

*1*-This first animation consists in some fishes navigating randomly each one on a path.
They have a life timing and the code re generates another fishes.The fishes are drawn with javascript code.It uses the free CAAT library (pointed on the 2 web links in the code.can download theses files and play at local environment also).
The codes are under licence MIT.they use object as actor, interpolator and scenes to build animations programmatly.
These 5 codes are awesome advanced animations produced by javascript using html5 canvas and show what this software can do ! Its a first part and i hope to bring others in next part.

Remember that all these codes work only with ie emulation (here ie11 one)
Select code and paste into prg +run.(internet must be connected).
All is tested on Windows8.1 only

 

*Adapted from http://labs.hyperandroid.com/static/CAAT-Samples/demos/demo1/path.html
*added web music with  wmplayer+exit fullscreen button

Set Safe Off
Local m.myvar
TEXT to m.myvar textmerge noshow
<!DOCTYPE html>
<html>
<script src='http://labs.hyperandroid.com/static/caat/lib/caat-min.js'> </script> ;
<script src='http://labs.hyperandroid.com/static/caat/lib/template.js' > </script> ;

<body  topmargin=0  leftmargin=0   bgcolor="black"  scroll="no"  oncontextmenu="window.close();return false;" >
<center><div id='experiment-holder'></div></center>


<Object Id="mediaplayer" classid="clsid:22d6f312-b0f6-11d0-94ab-0080c74c7e95" codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#version=5,1,52,701" standby="loading microsoft windows media player components..." Type="application/x-oleobject" Width="1" Height="1">
<Param Name="filename" Value="http://www.amclassical.com/mp3/amclassical_beethoven_fur_elise.mp3">
<Param Name="animationatstart" Value="true">
<Param Name="transparentatstart" Value="true">
<Param Name="autostart" Value="true">
<Param Name="showcontrols" Value="false">
<Param Name="ShowStatusBar" Value="false">
<Param Name="windowlessvideo" Value="true">
<Param Name='loop' Value='true'>
<embed src="http://www.amclassical.com/mp3/amclassical_beethoven_fur_elise.mp3" autostart="true" showcontrols="0" showstatusbar="0" Loop="1" bgcolor="white" Width="1" Height="1">
</Object>

<script>
//Document.getElementById('mediaplayer').Style.Display="none";
 /**
     * @license
     *
     * The MIT License
     * Copyright (c) 2010-2011 Ibon Tolosana, Hyperandroid || http://labs.hyperandroid.com/

     * Permission is hereby granted, free of charge, to any person obtaining a copy
     * of this software and associated documentation files (the "Software"), to deal
     * in the Software without restriction, including without limitation the rights
     * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
     * copies of the Software, and to permit persons to whom the Software is
     * furnished to do so, subject to the following conditions:

     * The above copyright notice and this permission notice shall be included in
     * all copies or substantial portions of the Software.

     * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
     * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
     * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
     * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
     * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
     * THE SOFTWARE.
     *
     */

(function() {
    CAAT.Fish= function() {
        CAAT.Fish.superclass.constructor.call(this);
        this.tail=  [];
        this.tail1= [];
        this.tail2= [];
        this.head1= [];
        this.head2= [];

        return this;
    };
    CAAT.Fish.prototype= {

        tail:       null,
        tail1:      null,
        tail2:      null,
        head1:      null,
        head2:      null,
        maxAngle:   45,
        bodyColor:  'red',
        f1:         0,
        f2:         0,
        f3:         0,
        f4:         0,
        tailSize:   0,
        timeOffset: 0,  // para que las colas se muevan a distinta frecuencia.
        headProportion:  0,  // proporcion desde donde tiene la cabeza.
        antihead:   false,
        headStart:  0,
        setBodyColor : function(color) {
            this.bodyColor= color;
            return this;
        },
        /**
         * born method must be called after Actor complete definition.
         */
        born : function() {
            this.f1= ((Math.random()*2)>>0)/1000 + .002;
            this.f2= ((Math.random()*2)>>0)/1000 + .002;
            this.f3= ((Math.random()*5)>>0)/1000;
            this.f4= ((Math.random()*5)>>0)/1000;

            this.tailSize= (Math.random()*3+2)>>0;
            this.timeOffset= (Math.random()*10000);

            this.antihead= Math.random()<.25;
            if ( this.antihead ) {
                this.headProportion= Math.random()*.25+.65;
                if ( this.headProportion<.8 ) {
                    this.headProportion=.8;
                }
            } else {
                this.headProportion= Math.random()*.25+.6;
            }

            this.maxAngle= 40+25*Math.random();

            var w= this.width;
            var h= this.height;

            var w2= w/2;
            var h2= h/2;

            this.headStart= this.antihead ? w : w*this.headProportion;

            this.tail[0]= 0;
            this.tail[1]= h2;

            /////////////--------------
            // tail son 1 y 2 punto de control, y el ultimo punto de la cubica.
            // ek primer punto fijo sera tail.
            this.tail1[0]= w2;
            this.tail1[1]= h2;

            this.tail1[2]= w2;
            this.tail1[3]= 0;

            this.tail1[4]= this.headStart;
            this.tail1[5]= 0;

            this.headpos= w;
            if ( this.antihead ) {
                this.headpos= w*this.headProportion;
            }

            this.head1[0]= this.headpos;
            this.head1[1]= 0;
            this.head1[2]= this.headpos;
            this.head1[3]= h2;

            this.head2[0]= this.headpos;
            this.head2[1]= h;
            this.head2[2]= this.headStart;
            this.head2[3]= h;

            this.tail2[0]= w2;
            this.tail2[1]= h;

            this.tail2[2]= w2;
            this.tail2[3]= h2;

            return this;
        },
        paint : function(director, time) {
            var ctx= director.ctx;

            time+= this.timeOffset;

            var w= this.width;
            var h= this.height;
            var w2= w/2;
            var w4= w2/2
            var h2= h/2;

            // .002 .003
            var ang= Math.cos(time*this.f1)*this.maxAngle*Math.sin(time*this.f2)*Math.PI/180;
            var px= w4-w4*Math.cos(ang);
            var py= w4*Math.sin(ang);

            this.tail[0]= px;
            this.tail[1]= h2+ py;

            var inc= -3*(Math.sin(time*.005)+Math.cos(time*.001))/2;

            this.tail1[0]= w4;
            this.tail1[1]= h2+inc;
            this.tail1[2]= w2;
            this.tail1[3]= inc;

            ///// curva de cabeza.
            /*
            this.tail1[5]= -inc;
            this.head1[1]= -inc;
            this.head1[3]= h2-inc;
            this.head2[1]= h-inc;
            this.head2[3]= h-inc;
            */

            this.tail2[0]= w2;
            this.tail2[1]= h+inc;
            this.tail2[2]= w4;
            this.tail2[3]= h2+inc;

            ctx.beginPath();
            ctx.fillStyle='orange';

            //////////////////////////////////////////////// START ALETAS
            var aletaSize= h2;      // ancho
            var aletaHeight= 7;   // alto aleta
            var aletaWidth= 5;
            var aletaPos= w*2/3 + aletaWidth;

            ctx.beginPath();
                ctx.moveTo( aletaPos, 2 );
                ctx.quadraticCurveTo(
                        aletaPos, -aletaHeight,
                        aletaPos-aletaSize, -aletaHeight-3*Math.sin(time*.002) );
                ctx.lineTo( aletaPos-aletaWidth, 2);
                ctx.closePath();
            ctx.fill();
            ctx.beginPath();
                ctx.moveTo( aletaPos, h-2 );
                ctx.quadraticCurveTo(
                        aletaPos, h+aletaHeight,
                        aletaPos-aletaSize, h+aletaHeight-3*Math.cos(time*.002) );
                ctx.lineTo( aletaPos-aletaWidth, h-2 );
                ctx.closePath();
            ctx.fill();
            //////////////////////////////////////////////// END ALETAS

            //////////////////////////////////////////////// START BODY
/*
            this.head1[3]= h2-inc ;

            // subir bajar cuerpo
            this.tail1[5]= inc;
            this.head2[3]= h+inc;
*/
            ctx.beginPath();
                ctx.moveTo( this.tail[0], this.tail[1] + this.tailSize );
                ctx.bezierCurveTo(
                        this.tail1[0], this.tail1[1],
                        this.tail1[2], this.tail1[3],
                        this.tail1[4], this.tail1[5] );
                ctx.quadraticCurveTo(
                        this.head1[0], this.head1[1],
                        this.head1[2], this.head1[3]
                        );
                ctx.quadraticCurveTo(
                        this.head2[0], this.head2[1],
                        this.head2[2], this.head2[3]
                        );
                ctx.bezierCurveTo(
                        this.tail2[0], this.tail2[1],
                        this.tail2[2], this.tail2[3],
                        this.tail[0], this.tail[1] - this.tailSize );
            ctx.closePath();
            ctx.fillStyle=this.bodyColor;
            ctx.fill();
            ctx.strokeStyle=this.bodyColor;
            ctx.stroke();
            //////////////////////////////////////////////// END BODY

            //////////////////////////////////////////////// START EYES
            ctx.beginPath();
            ctx.fillStyle='black';
            var eyeradius= h2/6;

            if ( this.antihead ) {
                ctx.arc(this.headpos-eyeradius*2, h2-h2/3, eyeradius, 0, 2*Math.PI, false );
                ctx.arc(this.headpos-eyeradius*2, h2+h2/3, eyeradius, 0, 2*Math.PI, false );

            } else {
                ctx.arc(w-w2/4, h2-h2/3, eyeradius, 0, 2*Math.PI, false );
                ctx.arc(w-w2/4, h2+h2/3, eyeradius, 0, 2*Math.PI, false );
            }
            ctx.fill();
            //////////////////////////////////////////////// END EYES
        }
    };

    extend( CAAT.Fish, CAAT.Actor );
})();

    (function() {
        /**
         * Startup it all up when the document is ready.
         * Change for your favorite frameworks initialization code.
         */
        window.addEventListener(
                'load',
                function() {
                    CAAT.modules.initialization.init(
                            <<sysmetric(1)>>, <<sysmetric(2)>>,
                            'experiment-holder',
                            [],
                            __fishpond
                            );
                },
                false);


        function __fishpond(director) {

            var scene= director.createScene();

            // when the scene is activated, avoid the director clearing the viewport since it'll be
            // totally erased by the background.
            scene.activated= function() {
                director.setClear(false);
            }
            var NP=20;
            var colors= ['red', 'blue', 'white', 'rgb(0,255,255)', 'yellow'];
            var gradient= director.crc.createLinearGradient(0,0,director.width,director.height);
            gradient.addColorStop(0,'#000000');
            gradient.addColorStop(1,'#00007f');

            var gr= new CAAT.ActorContainer().
                    setBounds(0,0,director.width,director.height).
                    setFillStyle(gradient).
                    enableEvents(false).
                    cacheAsBitmap();

            for( var i=0; i<NP; i++ ) {

                var fw= (100 + Math.random()*40*(Math.random()<.5?1:-1))>>0;
                var fh= (20+ Math.random()*5*(Math.random()<.5?1:-1))>>0;

                var inTime= i*1000;

                var pb = new CAAT.PathBehavior().
                        setPath(new CAAT.Path().setCubic(
                        -fw - Math.random() * 300,
                        Math.random() * director.height,

                        director.width * Math.random(),
                        Math.random() * director.height,

                        director.width * Math.random(),
                        Math.random() * director.height,

                        Math.random() < .5 ? director.width + fw + Math.random() * 150 : Math.random() * director.width,
                        Math.random() < .5 ? -director.height * Math.random() - 300 : director.height + Math.random() * director.height
                        )).
                        setFrameTime(scene.time + inTime, (20000 + 5000 * Math.random()) >> 0).
                        setCycle(true).
                        setAutoRotate(true).
                        addListener({
                                behaviorExpired : function(behavior, time, actor) {
                                    behavior.path.setCubic(
                                            -fw - Math.random() * 300,
                                            Math.random() * director.height,

                                            director.width * Math.random(),
                                            -Math.random() * director.height / 2 + Math.random() * director.height,

                                            director.width * Math.random(),
                                            -Math.random() * director.height / 2 + Math.random() * director.height,

                                            Math.random() < .5 ? director.width + fw + Math.random() * 150 : Math.random() * director.width,
                                            Math.random() < .5 ? -director.height * Math.random() - 300 : director.height + Math.random() * director.height
                                            );
                                    behavior.setFrameTime(scene.time, (20000 + 5000 * Math.random()) >> 0);
                                    actor.born();
                                },
                                behaviorApplied : function(actor, time, normalizedTime, value) {

                                }
                            });

                var f= new CAAT.Fish().
                        setBounds(300,400,fw,fh).
                        born().
                        setFrameTime( scene.time+inTime, Number.MAX_VALUE ).
                        setBodyColor(colors[i%colors.length]);

                f.addBehavior(pb);
                gr.addChild(f);
            }

            scene.addChild(gr);

        }

    })();

</script>

   </body>
</html>
ENDTEXT

Local m.lcdest
m.lcdest=Addbs(Sys(2023))+"test.html"
=Strtofile(m.myvar,m.lcdest)

Declare Integer BringWindowToTop In user32 Integer
Declare Integer SetWindowText In user32 Integer HWnd, String lpstring
Declare Integer Sleep In kernel32 Integer

apie=Newobject("internetexplorer.application")


With apie
    .Navigate(lcdest)
    .menubar=0
	.Toolbar=0
	.StatusBar=0
	.fullscreen=1
	.Visible=.T.
	BringWindowToTop(.HWnd)
	SetWindowText(.HWnd, "Text path  animation (F11 set/toggle FULLSCREEN)")

	Sleep(2000)

	.Visible=.T.
Endwith


 

Awesome html5 canvas animations-part1

*2*-The code draws many small circles as objects with trails and animate them.It uses the same library CAAT as the first code( js files are reached by internet-must be connected).Can download these 2 files and play locally.Can orient the objects directions with the mouse and with the 2 buttons(attract or repulse).

 

 

*http://labs.hyperandroid.com/static/CAAT-Samples/demos/demo1/path.html
*added web music with  wmplayer and exit fullscreen button
Local m.yrep
m.yrep=Addbs(Justpath(Sys(16,1)))
Set Defa To (yrep)

Set Safe Off
Local m.myvar



TEXT to m.myvar textmerge noshow
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
        <style>
            *{
                box-sizing: border-box;
                -moz-box-sizing: border-box;
                margin: 0;
                padding: 0;
                outline: none;
            }
            body {
                background: black;
                color: white;
                font-family: Helvetica;
                overflow: hidden;
            }
            #canvas{
                position: absolute;
                left: 0;
                top: 40px;
                right: 0;
                bottom: 0;
            }
            #credits{
                position: absolute;
                left: 0;
                bottom: 0;
                right: 0;
                color: white;
                font-size: 1em;
                padding: 10px;
                z-index: 10;
            }
            h1{
                font-size: 1em;
                float: left;
            }
            #credits p{
                float: left;
                font-style: italic;
                margin-left: .5em;
                border-left: 2px solid white;
                padding-left: .5em;
            }
            #credits p a{
                color: white;
            }
            ul{
                position: absolute;
                left: 0;
                top: 0;
                right: 0;
                height: 40px;
                list-style-type: none;
            }
            li{
                float: left;
                width: 25%;
                text-align: center;
            }
            li a{
                display: block;
                width: 100%%;
                padding: 10px;
                font-size: 1em;
                color: white;
                text-decoration: none;
                text-shadow: 0 -2px 0 #111;
            }
            li a:hover{
                background-color: #555;
            }
            li a.on{
                background-color: #b70000;
            }
        </style>
        <title>Multitouch boids</title>
    </head>
  <body  topmargin=0 leftmargin=0 bgcolor="bisque"  scroll="no"  oncontextmenu="window.close();return false;" >
    </body>
        <ul>
            <li><a id="resetBtn" href="#">Reset</a></li>
            <li><a id="attractBtn" class="on" href="#">Attract</a></li>
            <li><a id="repulseBtn" href="#">Repulse</a></li>
            <li><a href="Javascript:window.close()">Exit</a></li>
        </ul>
        <canvas id="canvas" ></canvas>


<object id="mediaplayer" classid="clsid:22d6f312-b0f6-11d0-94ab-0080c74c7e95" codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#version=5,1,52,701" standby="loading microsoft windows media player components..." type="application/x-oleobject" width="320" height="310">
<param name="filename" value="http://www.amclassical.com/mp3/amclassical_beethoven_fur_elise.mp3">
     <param name="animationatstart" value="true">
     <param name="transparentatstart" value="true">
     <param name="autostart" value="true">
     <param name="showcontrols" value="false">
     <param name="ShowStatusBar" value="false">
     <param name="windowlessvideo" value="true">
 <param name='loop' value='true'>
     <embed src="http://www.amclassical.com/mp3/amclassical_beethoven_fur_elise.mp3" autostart="true" showcontrols="0" showstatusbar="0" loop="1" bgcolor="white" width="320" height="310">
</object>

        <script>
          document.getElementById('mediaplayer').style.display="none";

            (function() {
                var lastTime = 0;
                var vendors = ['ms', 'moz', 'webkit', 'o'];
                for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
                    window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
                    window.cancelRequestAnimationFrame = window[vendors[x]+
                    'CancelRequestAnimationFrame'];
                }
                if (!window.requestAnimationFrame)
                window.requestAnimationFrame = function(callback, element) {
                    var currTime = new Date().getTime();
                    var timeToCall = Math.max(0, 16 - (currTime - lastTime));
                    var id = window.setTimeout(function() { callback(currTime + timeToCall); },
                    timeToCall);
                    lastTime = currTime + timeToCall;
                    return id;
                };

                if (!window.cancelAnimationFrame)
                    window.cancelAnimationFrame = function(id) {
                    clearTimeout(id);
                };
            }())

            var boids = [], numBoids = 100, globalSpeed = .5,
            centerOfMass = { x: 0, y: 0, z: 0 }, steerDistance = 1000,
            repulsion = false, neighbourDistance = 10000;

            var touches = [];

            var canvas = document.getElementById( 'canvas' ),
                ctx = canvas.getContext( '2d' );

            function createBoids() {

                boids = [];

                for( var j = 0; j < numBoids; j++ ) {

                    boids.push( {
                        position: {
                            x: Math.random() * window.innerWidth,
                            y: Math.random() * window.innerHeight
                        },
                        oPosition: {
                            x: 0,
                            y: 0
                        },
                        velocity: {
                            x: .5 - Math.random(),
                            y: .5 - Math.random()
                        },
                        speed: .85 + .15 * Math.random(),
                        id: j,
                        c: 0
                    } );

                }

            }

            function init(){

                if( window.location.hash ) {
                    var v = parseInt( window.location.hash.substr( 1 ), 10 );
                    if( v > 0 ) numBoids = v;
                }

                document.getElementById( 'resetBtn' ).addEventListener( 'click', function( e ) {
                    createBoids();
                    e.preventDefault();
                } );

                var attractBtn = document.getElementById( 'attractBtn' );
                var repulseBtn = document.getElementById( 'repulseBtn' );

                attractBtn.addEventListener( 'click', function( e ) {
                    repulsion = false;
                    attractBtn.className = 'on';
                    repulseBtn.className = '';
                    e.preventDefault();
                } );

                repulseBtn.addEventListener( 'click', function( e ) {
                    repulsion = true;
                    attractBtn.className = '';
                    repulseBtn.className = 'on';
                    e.preventDefault();
                } );



                function findTouchById( id ) {

                    for( var k = 0; k < touches.length; k++ ) {
                        if( touches[ k ].id == id ) {
                            return k;
                        }
                    }

                    return null;

                }

                canvas.addEventListener( 'mousedown', onTouchStart );
                canvas.addEventListener( 'touchstart', onTouchStart );

                function onTouchStart( event ) {

                    if( event.changedTouches ) {
                        for( var j = 0; j < event.changedTouches.length; j++ ){
                            var t = findTouchById( event.changedTouches[ j ].identifier );
                            if( t === null ) {
                                touches.push( {
                                    x: event.changedTouches[ j ].pageX,
                                    y: event.changedTouches[ j ].pageY,
                                    id: event.changedTouches[ j ].identifier
                                } );
                            } else {
                                touches[ t ].x = event.changedTouches[ j ].pageX;
                                touches[ t ].y = event.changedTouches[ j ].pageY;
                            }
                        }
                    } else {
                        touches.push( {
                            x: event.clientX,
                            y: event.clientY,
                            id: 0
                        } );
                    }

                    event.preventDefault();
                    return false;
                }

                canvas.addEventListener( 'mousemove', onTouchMove );
                canvas.addEventListener( 'touchmove', onTouchMove );

                function onTouchMove( event ) {

                    if( event.changedTouches ) {
                        for( var j = 0; j < event.changedTouches.length; j++ ){
                            var t = findTouchById( event.changedTouches[ j ].identifier );
                            if( t !== null ) {
                                touches[ t ].x = event.changedTouches[ j ].pageX;
                                touches[ t ].y = event.changedTouches[ j ].pageY;
                            }
                        }
                    } else {
                        if( touches[ 0 ] ) {
                            touches[ 0 ].x = event.clientX;
                            touches[ 0 ].y = event.clientY;
                        }
                    }

                    event.preventDefault();

                }

                canvas.addEventListener( 'mouseup', onTouchEnd );
                canvas.addEventListener( 'touchend', onTouchEnd );

                function onTouchEnd( event ) {

                    if( event.changedTouches ) {
                        for( var j = 0; j < event.changedTouches.length; j++ ) {
                            var t = findTouchById( event.changedTouches[ j ].identifier );
                            if( t !== null ) {
                                touches.splice( t, 1 );
                            }
                        }
                    } else {
                        touches = [];
                    }

                    event.preventDefault();

                }

                onWindowResize();

                createBoids();

                animate();

            }

        function draw() {

        //ctx.clearRect( 0, 0, canvas.width, canvas.height );
        ctx.globalAlpha = .1;
        ctx.fillStyle = '#000000';
        ctx.fillRect( 0, 0, canvas.width, canvas.height );
        ctx.globalAlpha = 1;

        ctx.lineWidth = 10;
        ctx.fillStyle = '#ffffff';
        ctx.lineCap = 'round';
        ctx.globalAlpha = 1;
        ctx.fillStyle = '#000000';

        for( var j = 0, m = boids.length; j < m; j++ ) {

            var b = boids[ j ];

            ctx.strokeStyle = '#ff00ff'
            if( b.c === 0 ) ctx.strokeStyle = 'rgb(255, 20, 10)';
            if( b.c === 1 ) ctx.strokeStyle = 'rgb(255, 216, 58)';
            if( b.c === 2 ) ctx.strokeStyle = 'rgb(223, 80, 0)';
            if( b.c === 3 ) ctx.strokeStyle = 'rgb(1, 129, 189)';
            if( b.c === 4 ) ctx.strokeStyle = 'rgb(73, 185, 73)';

            ctx.beginPath();
            ctx.lineWidth = 3 * ( 1 + 3 * b.speed );
            ctx.moveTo( b.oPosition.x, b.oPosition.y );
            ctx.lineTo( b.position.x, b.position.y );
            ctx.stroke();

        }

        /*ctx.fillStyle = '#000000';
        ctx.globalAlpha = 1;
        for( var j = 0; j < touches.length; j++ ) {
            ctx.beginPath();
            ctx.arc( touches[ j ].x, touches[ j ].y, 5, 0, 2 * Math.PI );
            ctx.fill();
        }*/

    }

    function steerTowardsCenter( b, neighbours ) {

        if( neighbours.length == 0 ) return { x: 0, y: 0, z: 0 };

        var centerOfMass = { x: 0, y: 0, z: 0 };

        for( var k = 0, m = neighbours.length; k < m; k++ ) {
            var b2 = neighbours[ k ];
            centerOfMass.x += b2.position.x;
            centerOfMass.y += b2.position.y;
        }

        centerOfMass.x /= neighbours.length;
        centerOfMass.y /= neighbours.length;

        var v = {
            x: .01 * ( centerOfMass.x - b.position.x ),
            y: .01 * ( centerOfMass.y - b.position.y )
        }

        return v;

    }

    function steerAwayFromNeighbours( b, neighbours ) {

        if( neighbours.length == 0 ) return { x: 0, y: 0, z: 0 };

        var sD = steerDistance;
        var v = { x: 0, y: 0, z: 0 }

        for( var k = 0, m = neighbours.length; k < m; k++ ) {
            var b2 = neighbours[ k ];
            var dx = b2.position.x - b.position.x;
            var dy = b2.position.y - b.position.y;
            var distance = dx * dx + dy * dy;
            if( distance < sD ) {
                v.x -= .1 * dx;
                v.y -= .1 * dy;
            }
        }

        return v;

    }

    function matchVelocity( b, neighbours ) {

        var v = { x: 0, y: 0, z: 0 }

        if( neighbours.length ) {

            for( var k = 0, m = neighbours.length; k < m; k++ ) {
                var b2 = neighbours[ k ];
                v.x += b2.velocity.x;
                v.y += b2.velocity.y;
            }

            v.x /= neighbours.length;
            v.y /= neighbours.length;

        }

        return {
            x: .0125 * ( v.x - b.velocity.x ),
            y: .0125 * ( v.y - b.velocity.y )
        }

    }

    function steerTowardsMouse( b ) {

        var x = 0, y = 0, c = 0;;
        for( var j = 0; j < touches.length; j++ ){
            if( j === b.c ) {
                x += ( repulsion?-1:1 ) * .001 * ( touches[ j ].x - b.position.x );
                y += ( repulsion?-1:1 ) * .001 * ( touches[ j ].y - b.position.y );
            }
        }

        return {
            x: x,
            y: y
        }

    }

    function repulseFromMouse( b ) {

        if( repulsion ) {

            var ax = 0, ay = 0;
            for( var j = 0; j < touches.length; j++ ) {
                var x = ( b.position.x - touches[ j ].x ),
                    y = ( b.position.y - touches[ j ].y ),
                    l = Math.sqrt( x * x + y * y ),
                    dx = x / l,
                    dy = y / l;
                    if( l > 10 ) l = 10;
                    l = 100 / l;
                    ax += .05 * dx * l;
                    ay += .05 * dy * l;
            }

            return {
                x: ax,
                y: ay
            }
        } else{
            return {
                x: 0,
                y: 0
            }
        }

    }

    function update() {

        var nD = neighbourDistance;

        var mt = touches.length;
        for( var j = 0, m = boids.length; j < m; j++ ) {
            var b = boids[ j ];
            for( var k = 0; k < touches.length; k++ ){
                if( k === b.id % mt ) {
                    b.c = k;
                }
            }
        }

        for( var j = 0, m = boids.length; j < m; j++ ) {

            var b = boids[ j ];
            var neighbours = [];

            for( k = 0, m = boids.length; k < m; k++ ) {

                var b2 = boids[ k ];
                if( b != b2 ) {
                    var dx = b2.position.x - b.position.x;
                    var dy = b2.position.y - b.position.y;
                    var distance = dx * dx + dy * dy;
                    if( distance < nD && b.c === b2.c ) {
                        neighbours.push( b2 );
                    }
                }
            }

            var v1 = steerTowardsCenter( b, neighbours );
            var v2 = steerTowardsMouse( b );
            var v3 = steerAwayFromNeighbours( b, neighbours );
            var v4 = matchVelocity( b, neighbours );

            b.velocity.x += v1.x + v2.x + v3.x + v4.x;
            b.velocity.y += v1.y + v2.y + v3.y + v4.y;

            var l = Math.sqrt( b.velocity.x * b.velocity.x + b.velocity.y * b.velocity.y );
            var norm = 1 / l;
            if( l > 10 ) l = 10;
            if( l < 2 ) l = 2;
            b.velocity.x *= b.speed * l * norm;
            b.velocity.y *= b.speed * l * norm;

            b.oPosition.x = b.position.x;
            b.oPosition.y = b.position.y;

            b.position.x += b.velocity.x * globalSpeed;
            b.position.y += b.velocity.y * globalSpeed;

            if( b.position.x < 0 || b.position.x > window.innerWidth ) b.velocity.x *= -1;
            if( b.position.y < 0 || b.position.y > window.innerHeight ) b.velocity.y *= -1;

        }

    }

    function animate() {

        update();
        draw();
        requestAnimationFrame( animate );

    }

    function onWindowResize() {
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
    }

    window.addEventListener( 'resize', onWindowResize );
    window.addEventListener( 'load', init )

    </script>


    </body>
</html>
ENDTEXT

Local m.lcdest
m.lcdest=Addbs(Sys(2023))+"test.html"
=Strtofile(m.myvar,m.lcdest)

Declare Integer BringWindowToTop In user32 Integer
Declare Integer SetWindowText In user32 Integer HWnd, String lpstring
Declare Integer Sleep In kernel32 Integer

apie=Newobject("internetexplorer.application")

With apie
    .Navigate(lcdest)
	.menubar=0
	.Toolbar=0
	.StatusBar=0
	.fullscreen=1
	.Visible=.T.
	BringWindowToTop(.HWnd)
	SetWindowText(.HWnd, "Text path  animation (F11 set/toggle FULLSCREEN)")

	Sleep(2000)

	.Visible=.T.
Endwith


 

Awesome html5 canvas animations-part1

*3*- this uses also the CAAT library.Create points objects randomly colored  and animate them .An oscillator text is added.

 

*http://labs.hyperandroid.com/static/CAAT-Samples/demos/demo1/path.html
set safe off
local m.myvar
text to m.myvar textmerge noshow
<!DOCTYPE html>
<html>
<script src='http://labs.hyperandroid.com/static/caat/lib/caat-min.js' ></script>
<script src='http://labs.hyperandroid.com/static/caat/lib/template.js'  ></script>

<body   bgcolor="black"  scroll="no"  oncontextmenu="window.close();return false;" ><br><br><br><br>
<center><div id='experiment-holder'>
</div></center>
<object id="mediaplayer" classid="clsid:22d6f312-b0f6-11d0-94ab-0080c74c7e95" codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#version=5,1,52,701" standby="loading microsoft windows media player components..." type="application/x-oleobject" width="1" height="1">
<param name="filename" value="http://yourlisten.com/player/director/17037018.mp3">
     <param name="animationatstart" value="true">
     <param name="transparentatstart" value="true">
     <param name="autostart" value="true">
     <param name="showcontrols" value="false">
     <param name="ShowStatusBar" value="false">
     <param name="windowlessvideo" value="true">
     <param name='loop' value='true'>
     <embed src="http://yourlisten.com/player/director/17037018.mp3" autostart="true" showcontrols="0" showstatusbar="0" loop="1" bgcolor="white" width="1" height="1">
</object>

<script>
  //document.getElementById('mediaplayer').style.display="none";
/**
     * @license
     *
     * The MIT License
     * Copyright (c) 2010-2011 Ibon Tolosana, Hyperandroid || http://labs.hyperandroid.com/

     * Permission is hereby granted, free of charge, to any person obtaining a copy
     * of this software and associated documentation files (the "Software"), to deal
     * in the Software without restriction, including without limitation the rights
     * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
     * copies of the Software, and to permit persons to whom the Software is
     * furnished to do so, subject to the following conditions:

     * The above copyright notice and this permission notice shall be included in
     * all copies or substantial portions of the Software.

     * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
     * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
     * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
     * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
     * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
     * THE SOFTWARE.
     *
     */

    (function() {

        var CW= <<sysmetric(1)>>
        var CH=<< sysmetric(2)>>
        /**
         * Startup it all up when the document is ready.
         * Change for your favorite frameworks initialization code.
         */
        window.addEventListener(
                'load',
                function() {
                    CAAT.modules.initialization.init(
                            CW, CH,
                            'experiment-holder',
                            [],
                            __accelerometer
                            );
                },
                false);


        function drawStarfield(ctx) {
            drawStars(ctx);

            for( var i=0; i<nStars; i++ ) {
                m_starData[i*4+2] -= speed;
                if (m_starData[i*4+2] < -dist) {
                    m_starData[i*4+2] = dist;
                    m_starData[i*4+0] = (((Math.random() > .5) ? 1 : -1) * (Math.random() * dist))>>0;
                    m_starData[i*4+1] = (((Math.random() > .5) ? 1 : -1) * (Math.random() * dist))>>0;
                }
            }

            rotate();
        }


        var nStars = 1000;
        var m_starData= [];
        var speed = 5;
        var STAR_DENSITY = 256;
        var dist = 256;
        var m_matrix= [];
        var xy = 0, xz = 0, yz = 0;

        function createStars() {
            rotate();

            var i;
            for( i=0; i<nStars*4; i++ ) {
                m_starData.push(0);
            }

            for ( i = 0; i < nStars; i++ ) {
                m_starData[i*4+0] = ((Math.random() > .5) ? 1 : -1) * (Math.random() * dist)>>0;
                m_starData[i*4+1] = ((Math.random() > .5) ? 1 : -1) * (Math.random() * dist)>>0;
                m_starData[i*4+2] = ((Math.random() > .5) ? 1 : -1) * (Math.random() * dist)>>0;

                var d = Math.random();
                if (d < .25) {
                    m_starData[i*4+3] = '#ff0000';
                } else if (d < .50) {
                    m_starData[i*4+3] = '#00ff00';
                } else if (d < .75) {
                    m_starData[i*4+3] = '#0000ff';
                } else {
                    m_starData[i*4+3] = '#ffffff';
                }
            }
        }

        function drawStars(ctx) {
            var i,l;

            for ( i = 0, l=nStars; i < l; i++ ) {

                var xx = m_starData[i*4+0];
                var yy = m_starData[i*4+1];
                var zz = m_starData[i*4+2];

                var x = xx * m_matrix[0] + yy * m_matrix[1] + zz * m_matrix[2] + m_matrix[3];
                var y = xx * m_matrix[4] + yy * m_matrix[5] + zz * m_matrix[6] + m_matrix[7];
                var z = xx * m_matrix[8] + yy * m_matrix[9] + zz * m_matrix[10] + m_matrix[11];

                if (z > 0) {

                    var xp = ( CW >> 1 ) + (x * 256) / z;
                    var yp = ( CH >> 1 ) + (y * 256) / z;

                    var s=0;
                    if (z < 128) {
                        s = 4;
                    } else if (z < 256) {
                        s = 2;
                    } else {
                        s = 1;
                    }

                    ctx.fillStyle= m_starData[i*4+3];
                    ctx.fillRect( xp, yp, s, s );
                }
            }
        }

        function rotate() {

            var sxy = Math.sin(xy);
            var sxz = Math.sin(xz);
            var syz = Math.sin(yz);
            var cxy = Math.cos(xy);
            var cxz = Math.cos(xz);
            var cyz = Math.cos(yz);

            m_matrix[  0 ] = cxz * cxy;
            m_matrix[  1 ] = -cxz * sxy;
            m_matrix[  2 ] = sxz;
            m_matrix[  3 ] = 0;
            m_matrix[  4 ] = syz * sxz * cxy + sxy * cyz;
            m_matrix[  5 ] = cyz * cxy - syz * sxz * sxy;
            m_matrix[  6 ] = -syz * cxz;
            m_matrix[  7 ] = 0;
            m_matrix[  8 ] = syz * sxy - cyz * sxz * cxy;
            m_matrix[  9 ] = cyz * sxz * sxy + syz * cxy;
            m_matrix[  10] = cyz * cxz;
            m_matrix[ 11 ] = dist;
            m_matrix[ 12 ] = 0;
            m_matrix[ 13 ] = 0;
            m_matrix[ 14 ] = 0;
            m_matrix[ 15 ] = 1;
        }


        function __accelerometer(director) {

            createStars();
            var i;
            var scene = director.createScene();

            scene.activated= function() {
                director.setClear(false);
            };

            var root= new CAAT.ActorContainer().setBounds(0,0,director.width,director.height);
            scene.addChild(root);
            root.paint= function(dirctor, time) {
                var ctx= director.ctx;
                ctx.fillStyle='black';
                ctx.fillRect(0,0,director.width,director.height);
                drawStarfield(ctx);
            };

            __scene11_text(director, scene);

            var text = new CAAT.TextActor().
                    setFont("36px sans-serif").
                    setText("Rotate Device-Rightclick or ALT+F4 to close").
                    setTextFillStyle('red').
                    setOutlineColor('#ffff00').
                    setOutline(true).
                    calcTextSize(director).
                    cacheAsBitmap();
            scene.addChild(text.setLocation((director.canvas.width - text.width) / 2,
                    (director.canvas.height - text.height) / 2) );

            scene.onRenderEnd = function(director, time) {
                var rx = CAAT.rotationRate.gamma;

                //rx/=10; // 9.8 m/s^2

                var ixy= -rx * Math.PI / 180;
                text.setRotation(ixy);

                xy+= -ixy/10;
                yz+= -CAAT.rotationRate.beta * Math.PI/ 180 / 10;

            };
        }

        function __scene11_text(director, scene) {
            var gradient = director.crc.createLinearGradient(0, 0, 0, 50);
            gradient.addColorStop(0, 'orange');
            gradient.addColorStop(0.5, 'yellow');
            gradient.addColorStop(1, '#7f00ff');

            var cc = new CAAT.ActorContainer().
                    setBounds(550, 50, 150, 100).
                    create().
                    enableEvents(false).
                    addBehavior(
                    new CAAT.RotateBehavior().
                            setCycle(true).
                            setFrameTime(0, 4000).
                            setValues(-Math.PI / 8, Math.PI / 8, .50, 0).
                            setInterpolator(
                            new CAAT.Interpolator().createExponentialInOutInterpolator(3, true)
                            )
                    );
            scene.addChild(cc);

            var text = new CAAT.TextActor().
                    setFont("50px sans-serif").
                    setText("Accelerometer").
                    setTextFillStyle(gradient).
                    setOutline(true).
                    calcTextSize(director).
                    cacheAsBitmap();
            cc.addChild(text.setLocation((cc.width - text.width) / 2, 0));

            var text2 = new CAAT.TextActor().
                    setFont("50px sans-serif").
                    setText("Enabled").
                    calcTextSize(director).
                    setTextFillStyle(gradient).
                    setOutline(true).
                    cacheAsBitmap();
            cc.addChild(text2.setLocation((cc.width - text2.width) / 2, 50));
        }


    })();


</script>

   </body>
</html>
endtext

local m.lcdest
m.lcdest=addbs(sys(2023))+"test.html"
=strtofile(m.myvar,m.lcdest)

Declare Integer BringWindowToTop In user32 Integer
Declare Integer SetWindowText In user32 Integer HWnd, String lpstring
Declare Integer Sleep In kernel32 Integer

apie=Newobject("internetexplorer.application")



with apie
  .Navigate(lcdest)
    .menubar=0
	.Toolbar=0
	.fullscreen=1
	.Visible=.T.
	BringWindowToTop(.HWnd)
	SetWindowText(.HWnd, "Text path  animation (F11 set/toggle FULLSCREEN)")

	sleep(2000)
	
	    	.visible=.t.
Endwith


 

Awesome html5 canvas animations-part1

*4* -

this code draws a modifiable compound  path and move over an object  as web image  by the code.An easing scenario can be choosed (click by the mouse) to make the correspondant dynamic animation on the path.

 

 


*http://labs.hyperandroid.com/static/CAAT-Samples/demos/demo1/path.html
Set Safe Off
Local m.myvar
TEXT to m.myvar textmerge noshow
<!DOCTYPE html>
<html>
<script src='http://labs.hyperandroid.com/static/caat/lib/caat-min.js'></script>

<script src='http://labs.hyperandroid.com/static/caat/lib/template.js' ></script>


 <body  topmargin=0 leftmargin=0 bgcolor="bisque"  scroll="no"  oncontextmenu="window.close();return false;" >

<center><div id='experiment-holder'>
</div></center>
   </body>
<script>

    (function() {
        /**
         * Startup it all up when the document is ready.
         * Change for your favorite frameworks initialization code.
         */
        window.addEventListener(
                'load',
                function() {
                    CAAT.modules.initialization.init(
                            800, 500,
                            'experiment-holder',
                            [
                                {id:'fish', url:'http://labs.hyperandroid.com/static/CAAT-Samples/demos/demo-resources/img/anim2.png'}
                            ],
                            __scene1
                            );
                },
                false);

        /**
         * Create an Actor for every available interpolator/easing function built in CAAT.
         * This Actors are indeed InterpolatorActor, an out-of-the-box scene actor which draws
         * a function.
         * Interpolators will be laid out in a OSX Dock fashion. To do so, there's an special
         * CAAT.Dock actor. This Docking element allows to define its direction, whether
         * horizontal or vertical, and the direction to anchor its contained elements zoom.
         *
         * @param director {CAAT.Director}
         * @param scene {CAAT.Scene}
         * @param pathBehavior {CAAT.PathBehavior} The path to modify traverse speed for.
         */
        function generateInterpolators(director, scene, pathBehavior) {

            var lerps = CAAT.Interpolator.prototype.enumerateInterpolators();

            /**
             * Lay interpolators out on 20 rows, and construct as much as Dock
             * elements to hold the whole collection of interpolators.
             */
            var cols = 20;
            var j = 0, i = 0;
            var rows = lerps.length / 2 / cols;
            var min = 20;
            var max = 45;
            var selectedInterpolatorActor = null;

            // generate interpolator actors.
            for (j = 0; j < rows; j++) {

                var root = new CAAT.Dock().
                        initialize(scene).
                        setBounds(
                            director.canvas.width - (j + 1) * max,
                            0,
                            max,
                            director.canvas.height).
                        setSizes(min, max).
                        setApplicationRange(3).
                        setLayoutOp(CAAT.Dock.prototype.OP_LAYOUT_RIGHT);

                scene.addChild(root);

                for (i = 0; i < cols; i++) {

                    if (j * cols + i >= lerps.length) {
                        break;
                    }

                    var actor = new CAAT.InterpolatorActor().
                            create().
                            setInterpolator(lerps[(j * cols + i) * 2]).
                            setBounds(0, 0, min, min).
                            setStrokeStyle('blue');

                    actor.mouseExit = function(mouseEvent) {
                        if (this != selectedInterpolatorActor) {
                            this.setFillStyle(null);
                        }
                    }
                    actor.mouseEnter = function(mouseEvent) {
                        if (this != selectedInterpolatorActor) {
                            this.setFillStyle('#f0f0f0');
                        }
                    }
                    actor.mouseClick = function(mouseEvent) {
                        if (null != selectedInterpolatorActor) {
                            selectedInterpolatorActor.setFillStyle(null);
                        }
                        selectedInterpolatorActor = mouseEvent.source;
                        this.setFillStyle('#00ff00');
                        selectedInterpolatorActor = mouseEvent.source;

                        pathBehavior.setInterpolator(mouseEvent.source.getInterpolator());
                    }

                    root.addChild(actor);
                }

                root.layout();
            }
        }

        function __scene1(director) {

            var scene = director.createScene();

            var path= new CAAT.Path().
                            beginPath(200, 200).
                            addCubicTo(300, 15, 400, 10, 500, 200).
                            addQuadricTo(550, 300, 450, 350).
                            addQuadricTo(400, 400, 350, 200).
                            addCubicTo(100, 300, 300, 450, 10, 400).
                            addQuadricTo(40, 200, 200, 200).
                            closePath();
            /**
             * Show a Path on screen and allow manipulation of its path by showing handles.
             */
            var pa = new CAAT.PathActor().
                    setBounds(0, 0, 800, director.canvas.height).
                    create().
                    setPath(path);

            /**
             * Create a fish which will traverse the path.
             */
            var fish = new CAAT.Actor().
                    setBackgroundImage(
                            new CAAT.SpriteImage().
                                    initialize(director.getImage('fish'), 1, 3),
                            true).
                    setAnimationImageIndex([0,1,2,1]).
                    setChangeFPS(300).
                    enableEvents(false);

            // path measurer behaviour
            var pb = new CAAT.PathBehavior().
                    setPath(path).
                    setFrameTime(0, 20000).
                    setCycle(true).
                    setAutoRotate(true, CAAT.PathBehavior.autorotate.LEFT_TO_RIGHT).
                    setTranslation(fish.width / 2, fish.height / 2);

            fish.addBehavior(pb);


            scene.addChild(pa);
            addDescription(director, scene);
            scene.addChild(fish);

            generateInterpolators(director, scene, pb);

            return scene;
        }

        function addDescription(director, scene) {
            var cc1 = new CAAT.ActorContainer().
                    setBounds(0, 30, 280, 110).
                    create().
                    enableEvents(false);
            scene.addChild(cc1);

            cc1.addBehavior(
                    new CAAT.RotateBehavior().
                            setCycle(true).
                            setFrameTime(0, 4000).
                            setValues(-Math.PI / 8, Math.PI / 8, .50, 0).    // anchor at 50%, 0%
                            setInterpolator(
                            new CAAT.Interpolator().createExponentialInOutInterpolator(3, true))
                    );

            var gradient = director.crc.createLinearGradient(0, 0, 0, 30);
            gradient.addColorStop(0, '#00ff00');
            gradient.addColorStop(0.5, 'red');
            gradient.addColorStop(1, 'blue');

            var text = new CAAT.TextActor().
                    setFont("20px sans-serif").
                    setText("Conpound Path").
                    calcTextSize(director).
                    setTextFillStyle(gradient).
                    setOutline(true).
                    cacheAsBitmap();
            cc1.addChild(text.setLocation((cc1.width - text.textWidth) / 2, 0));

            var text2 = new CAAT.TextActor().
                setFont("20px sans-serif").
                setText("Quadric,Cubic,Line segments").
                calcTextSize(director).
                setTextFillStyle(gradient).
                setOutline(true).
                cacheAsBitmap();

            cc1.addChild(text2.setLocation((cc1.width - text2.textWidth) / 2, 20));

            var text4 = new CAAT.TextActor().
                    setFont("20px sans-serif").
                    setText("Fish Path").
                    calcTextSize(director).
                    setTextFillStyle(gradient).
                    setOutline(true).
                    cacheAsBitmap();
            cc1.addChild( text4.setLocation((cc1.width - text4.textWidth) / 2, 50) );

            var text3 = new CAAT.TextActor().
                    setFont("20px sans-serif").
                    setText("Interpolators").
                    calcTextSize(director).
                    setTextFillStyle(gradient).
                    setOutline(true).
                    cacheAsBitmap();
            cc1.addChild(text3.setLocation((cc1.width - text3.textWidth) / 2, 70));
        };

    })();


</script>

   </body>
</html>
ENDTEXT

Local m.lcdest
m.lcdest=Addbs(Sys(2023))+"test.html"
=Strtofile(m.myvar,m.lcdest)

Declare Integer BringWindowToTop In user32 Integer
Declare Integer SetWindowText In user32 Integer HWnd, String lpstring
Declare Integer Sleep In kernel32 Integer

apie=Newobject("internetexplorer.application")



With apie
    .Navigate(lcdest)
	.menubar=0
	.Toolbar=0
	.StatusBar=0
	.Height=600
	.Width=800
	.Top=(Sysmetric(2)-.Height)/2
	.Left=(Sysmetric(1)-.Width)/2
	.Visible=.T.
	BringWindowToTop(.HWnd)
	SetWindowText(.HWnd, "Text path  animation (F11 set/toggle FULLSCREEN)")

	Sleep(2000)

	.Visible=.T.
Endwith


 

Awesome html5 canvas animations-part1

*5*

The text can be drawn on a path with html5 canvas.The CAAT library can modify interactively the path with the text on.Drag the points with mouse to see the result.

 

*adapted from http://labs.hyperandroid.com/static/CAAT-Samples/demos/demo5/text-on-path.html
*Text paths

Set Safe Off
Local m.myvar
TEXT to m.myvar textmerge noshow
<!DOCTYPE html>
<html>
<script src='http://labs.hyperandroid.com/static/caat/lib/caat-min.js'>  </script>       


<script src='http://labs.hyperandroid.com/static/caat/lib/template.js' ></script >                     
                                 
<body   bgcolor="black"  scroll="no"  oncontextmenu="window.close();return false;" >
<div id='experiment-holder'>
</div>
<script>

    (function() {
        /**
         * Startup it all up when the document is ready.
         * Change for your favorite frameworks initialization code.
         */
        window.addEventListener(
                'load',
                function() {
                    CAAT.modules.initialization.init(
                            <<sysmetric(1)>>, <<sysmetric(2)>>,
                            'experiment-holder',
                            [],
                            textOnPath
                            );
                },
                false);

        function textOnPath(director) {

            var scene = director.createScene();

            var p = new CAAT.Path().
                    beginPath(25, 250).
                    addCubicTo(25, 0, 275, 0, 275, 250).
                    addCubicTo(275, 400, 525, 400, 525, 250).
                    addCubicTo(525, 0, 775, 0, 775, 250).
                    addCubicTo(775, 500, 25, 500, 25, 250).
                    endPath();


            // actor de path para poder verlo y manipularlo
            var pa = new CAAT.PathActor().
                    setPath(p).
                    setBounds(0, 0, director.canvas.width, director.canvas.height);
            scene.addChild(pa);

            var gradient = director.crc.createLinearGradient(0, 0, 0, -40);
            gradient.addColorStop(0, '#ffff00');
            gradient.addColorStop(0.5, '#00ffff');
            gradient.addColorStop(1, 'blue');

            var text = new CAAT.TextActor().
                setFont("40px sans-serif").
                setText("Text on path, easily traverse a path with text.").
                setTextAlign("left").
                setTextFillStyle(gradient).
                setTextBaseline("bottom").
                setPath(
                    p,
                    new CAAT.Interpolator().createLinearInterpolator(false),
                    30000);
            scene.addChild(text);

            var gradient2 = director.crc.createLinearGradient(0, 0, 0, 40);
            gradient2.addColorStop(0, '#0000ff');
            gradient2.addColorStop(0.5, '#ff0000');
            gradient2.addColorStop(1, '#ffff00');

            var text2 = new CAAT.TextActor().
                setFont("40px sans-serif").
                setText("Text under path   :D").
                setTextAlign("left").
                setTextFillStyle(gradient2).
                setTextBaseline("top").
                setPath(
                    p,
                    new CAAT.Interpolator().createExponentialInOutInterpolator(3)).
                setPathTraverseDirection( CAAT.TextActor.TRAVERSE_PATH_BACKWARD );
            scene.addChild(text2);


            createText(director, scene);
        }

        function createText(director, scene) {
            var cc1 = new CAAT.ActorContainer().
                    setBounds(255, 30, 280, 120).
                    enableEvents(false);
            scene.addChild(cc1);

            var rb = new CAAT.RotateBehavior().
                    setCycle(true).
                    setFrameTime(0, 4000).
                    setValues( -Math.PI / 8, Math.PI / 8, .50, 0 ).
                    setInterpolator(
                            new CAAT.Interpolator().createCubicBezierInterpolator(
                                    {x:0,y:0},
                                    {x:1,y:0},
                                    {x:0,y:1},
                                    {x:1,y:1},
                                    true))
            cc1.addBehavior(rb);

            var gradient = director.crc.createLinearGradient(0, 0, 0, 30);
            gradient.addColorStop(0, 'black');
            gradient.addColorStop(0.5, 'gray');
            gradient.addColorStop(1, '#d0d0d0');

            var text = new CAAT.TextActor().
                    setFont("40px sans-serif").
                    setText("Text on Path").
                    calcTextSize(director).
                    setTextAlign("center").
                    setTextFillStyle(gradient).
                    setOutline(true).
                    cacheAsBitmap();
            cc1.addChild(text.setLocation((cc1.width - text.width) / 2, 0));

            var text2 = new CAAT.TextActor().
                    setFont("40px sans-serif").
                    setTextAlign("center").
                    setText("Interpolated").
                    calcTextSize(director).
                    setTextFillStyle(gradient).
                    setOutline(true).
                    cacheAsBitmap();
            cc1.addChild(text2.setLocation((cc1.width - text2.width) / 2, 40));

            var text4 = new CAAT.TextActor().
                    setFont("40px sans-serif").
                    setTextAlign("center").
                    setText("As well").
                    calcTextSize(director).
                    setTextFillStyle(gradient).
                    setOutline(true).
                    cacheAsBitmap();
            cc1.addChild(text4.setLocation((cc1.width - text4.width) / 2, 80));
        }

    })();

</script>

   </body>
</html>
ENDTEXT

Local m.lcdest
m.lcdest=Addbs(Sys(2023))+"test.html"
=Strtofile(m.myvar,m.lcdest)

Declare Integer BringWindowToTop In user32 Integer
Declare Integer SetWindowText In user32 Integer HWnd, String lpstring
Declare Integer Sleep In kernel32 Integer

apie=Newobject("internetexplorer.application")

With apie
    .Navigate(lcdest)
	.menubar=0
	.Toolbar=0
	.StatusBar=0
	.fullscreen=1
	.Visible=.T.
	BringWindowToTop(.HWnd)
	SetWindowText(.HWnd, "Text path  animation (F11 set/toggle FULLSCREEN)")

	Sleep(2000)

	.Visible=.T.
Endwith


 

Awesome html5 canvas animations-part1
To be informed of the latest articles, subscribe:
Comment on this post