Calling function inside jQuery returns wrong result

98 views Asked by At

I have the following javascript code that runs fine if called outside the jQuery function on the bottom. I don't know what I am doing wrong.

Bresenham Algorithm:

function bresenham(x0,y0,x1,y1){
    var bresenham = [];

    var x = 0;
    var dx = x1-x0;
    var dy = y1-y0;

    var D = 2 * dy - dx;
    bresenham.push(x0 + "," + y0);
    var y = y0;

    for (x = x0+1;x<=x1;x++){
        if (D>0){
            y = y+1;
            bresenham.push(x + "," + y);
            D = D + (2*dy - 2*dx);
        } else {
            bresenham.push(x + "," + y);
            D = D + (2*dy);
        }
    }
    return bresenham;
};

JQuery:

$(document).ready(function(){
    $(".button").click(function(){
        $("div#output p").remove();

        var x0 = $('input[name=x0]').val();
        var y0 = $('input[name=y0]').val();
        var x1 = $('input[name=x1]').val();
        var y1 = $('input[name=y1]').val();

        var bres = bresenham(x0,y0,x1,y1);
        console.log(bres);
    });
});

If I input: x0 = 1, y = 0 and x1 = 15, y2 = 9

it outputs: ["1,0", "11,01", "12,01", "13,011", "14,0111", "15,0111"]

1

There are 1 answers

0
depperm On BEST ANSWER

I would change

$(document).ready(function(){
    $(".button").click(function(){
        $("div#output p").remove();

        var x0 = $('input[name=x0]').val();
        var y0 = $('input[name=y0]').val();
        var x1 = $('input[name=x1]').val();
        var y1 = $('input[name=y1]').val();

        var bres = bresenham(x0,y0,x1,y1);
        console.log(bres);
    });
});

to

$(document).ready(function(){
    $(".button").click(function(){
        $("div#output p").remove();

        var x0 = parseInt($('input[name=x0]').val());
        var y0 = parseInt($('input[name=y0]').val());
        var x1 = parseInt($('input[name=x1]').val());
        var y1 = parseInt($('input[name=y1]').val());

        var bres = bresenham(x0,y0,x1,y1);
        console.log(bres);
    });
});