0

I've got a script that creates a gradient by shading cells based on their distance from a set of coordinates. What I want to do is make the gradient circular rather than the diamond shape that it currently is. You can see an en example here: http://jsbin.com/uwivev/9/edit

var row = 5, col = 5, total_rows = 20, total_cols = 20;

$('table td').each(function(index, item) {

    // Current row and column        
    var current_row = $(item).parent().index(), 
        current_col = $(item).index();

    // Percentage based on location, always using positive numbers
    var percentage_row = Math.abs(current_row-row)/total_rows;
    var percentage_col = Math.abs(current_col-col)/total_cols;

    // I'm thinking this is what I need to change to achieve the curve I'm after
    var percentage = (percentage_col+percentage_row)/2;

    $(this).find('div').fadeTo(0,percentage*3);

});

If you can give me hand with the right maths function to get the curve I'm after that would be great! Thanks!

Darren

frontendbeast
  • 1,043
  • 4
  • 13
  • 28

3 Answers3

0

You can use the square of the distance formula:

((current_row - row)*(current_row - row) + (current_col - col)*(current_col - col))

then multiply it by whatever scale factor you need.

Matt Gregory
  • 8,074
  • 8
  • 33
  • 40
0

Here is a circle drawing procudure I wrote many moons ago in Pascal which you can use as pseudo code to understand how to color pixels at the radius from an (X,Y) and work your way in. Multiple shrinking circles should cover the entire area you need. The code also gives you the formula for accessing the radius.

 PROCEDURE DrawCircle(X,Y,Radius:Integer);
 VAR A,B,Z:LongInt;
 BEGIN
  Z:=Round(Sqrt(Sqr(LongInt(Radius))/2));
  FOR A:=Z TO Radius DO
   FOR B:=0 TO Z DO
     IF Radius=Round(Sqrt(A*A+B*B)) THEN
      BEGIN
       PutPixel(X+A,Y+B,8);
       PutPixel(X+A,Y-B,9);
       PutPixel(X-A,Y+B,10);
       PutPixel(X-A,Y-B,11);
       PutPixel(X+B,Y+A,12);
       PutPixel(X+B,Y-A,13);
       PutPixel(X-B,Y+A,14);
       PutPixel(X-B,Y-A,15);
      END;
 END;

NB: "Longint()" is a compiler typecast for larger numeric computations so don't let that worry you.

NB: Inner-most brackets are executed first.

John Citizen
  • 184
  • 1
  • 2
  • 10
0
// Current row and column        
var current_row = $(item).parent().index(), 
    current_col = $(item).index();

// distance away from the bright pixel
var dist = Math.sqrt(Math.pow(current_row - row, 2) + Math.pow(current_col - col, 2))

// do something with dist, you might change this
var percentage = dist / total_cols;

$(this).find('div').fadeTo(0,percentage*3);
James
  • 20,957
  • 5
  • 26
  • 41