open in new window | flash version

Demos : Water Surface

Code:

<html>
<head>
     <script type="text/javascript" src="//lib.ivank.net/ivank.js"></script>
     <script type="text/javascript">
          var stage, s, n=40, clicked = false, calm;
          var rad = Math.round(n/12);
          
          var h = [];  // buffers for heights
          var v = [];  // buffers for velocities
          var vrt = [];  // vertices
          var ind = [];  // indices
          
          function Start()
          {
               stage = new Stage("c");
               var bg = new Bitmap( new BitmapData("winter2.jpg") );
               bg.scaleX = bg.scaleY = stage.stageHeight/512; 
               stage.addChild(bg);
               
               calm = stage.stageHeight*0.6;
               
               s = new Sprite();
               stage.addChild(s);
               stage.addEventListener(Event.ENTER_FRAME, onEF);
               stage.addEventListener(MouseEvent.MOUSE_DOWN, onMD);
               stage.addEventListener(MouseEvent.MOUSE_UP  , onMU);
               stage.addEventListener(MouseEvent.MOUSE_MOVE, onMM);
               initWaves(stage.stageWidth, stage.stageHeight);
          }
          
          function initWaves(wi, hi)
          {
               var step = wi/(n-1);
               for(var i=0; i < n; i++) {h.push(calm); v.push(0);}
               for(var i=0; i < n  ; i++) vrt.push(i*step,calm,   i*step,hi); 
               for(var i=0; i < n-1; i++) ind.push(2*i,2*i+1,2*i+2,  2*i+1,2*i+2,2*i+3);
          }
          
          function onEF(e)
          {
               for(var i=0; i<n; i++)
               {
                    // computing velocity from neighbouring heights
                    v[i] += ((he(i-1)+he(i+1)) + calm) /3 - h[i];
                    v[i] *= 0.98;	// damping
                    h[i] += v[i] * 0.05;
                    vrt[i*4+1] = h[i];
               }
               s.graphics.clear();
               s.graphics.beginFill(0x4466aa, 0.5);
               s.graphics.drawTriangles(vrt, ind);
          }
          
          function he(i)   { return h[(i+n)%n]; }	// "cycled" access to array 'h'
          
          function onMD(e) { clicked = true; onMM(); }
          function onMU(e) { clicked = false; }
          function onMM(e)
          {
               var i = Math.round(n*stage.mouseX/stage.stageWidth);
               if(clicked) if(i>rad && i<n-rad) pushAt(i);
          }
          
          function pushAt(i)
          {
               for(var j=-rad; j<rad; j++)
                    h[i+j] += Math.cos(j*Math.PI*0.5/rad)*15;
          }
     </script>
</head>
<body onload="Start();"><canvas id="c"></canvas></body>
</html>