Distance Line Gradient

Actionscript:
  1. [SWF(width=600,height=500,frameRate=30)]
  2. var canvas:BitmapData=new BitmapData(400,400,false,0x000000);
  3. addChild(new Bitmap(canvas));
  4.  
  5. var size:Number=canvas.width*canvas.height;
  6. var w:Number=canvas.width;
  7. var pix:Vector.<uint> = new Vector.<uint>(size);
  8.  
  9. addEventListener(Event.ENTER_FRAME, onLoop);
  10. function onLoop(evt:Event):void {
  11.     canvas.lock();
  12.        
  13.     var i:int = size;
  14.     var x1:Number=mouseX;
  15.     var y1:Number=mouseY;
  16.     var x2:Number=250;
  17.     var y2:Number=250;
  18.     var dx:Number=x2-x1;
  19.     var dy:Number=y2-y1;
  20.     var denom:Number =  1/(dx * dx + dy * dy);
  21.     if (dx==0&&dy==0) {
  22.             x2+=1;
  23.             y2+=1;
  24.             dx=dy=1;
  25.     }
  26.  
  27.     while( --i> -1 ){
  28.         var xp:int= i % w;
  29.         var yp:int = i / w;
  30.         var u:Number = ((xp - x1) * dx + (yp - y1) * dy) * denom;
  31.  
  32.         var closestX:Number;
  33.         var closestY:Number;
  34.         if (u<0) {
  35.             closestX=x1;
  36.             closestY=y1;
  37.         } else if (u> 1) {
  38.             closestX=x2;
  39.             closestY=y2;
  40.         } else {
  41.             closestX=x1+u*dx;
  42.             closestY=y1+u*dy;
  43.         }
  44.         var dfx:Number=closestX-xp;
  45.         var dfy:Number=closestY-yp;
  46.         var d:Number=255-Math.sqrt(dfx*dfx+dfy*dfy);
  47.         if (d<0) d=0;
  48.          pix[i]=uint(d);
  49.     }
  50.     canvas.setVector(canvas.rect, pix);
  51.     canvas.unlock();
  52. }

This didn't come out as interesting as I thought it would for some reason - just used the technique from the last two posts to draw a gradient. Event though it's visually boring, it does show how I went about inlining the function from yesterday... so I figured I'd post it.

This entry was posted in BitmapData, Vector, graphics algorithms and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*