Search code examples
javascriptmathtrigonometryeasing

Get curved result set rather than angular in JavaScript (maths help needed)


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


Solution

  • // 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);