Bresenham algorithm in Javascript

后端 未结 2 1472
清酒与你
清酒与你 2020-11-27 03:41

I need a fast algorithm for calculating coordinates for a line between two points. I tried to find good JavaScript Bresenham implementation, but there are too many and quite

2条回答
  •  情书的邮戳
    2020-11-27 04:30

    Disclaimer: I extracted this answer from the OPs question. Answers should not be contained in the question itself.


    Answer provided by Boris Hamanov:

    Thanks everybody! This is what I came with at the end:

    function calcStraightLine (startCoordinates, endCoordinates) {
        var coordinatesArray = new Array();
        // Translate coordinates
        var x1 = startCoordinates.left;
        var y1 = startCoordinates.top;
        var x2 = endCoordinates.left;
        var y2 = endCoordinates.top;
        // Define differences and error check
        var dx = Math.abs(x2 - x1);
        var dy = Math.abs(y2 - y1);
        var sx = (x1 < x2) ? 1 : -1;
        var sy = (y1 < y2) ? 1 : -1;
        var err = dx - dy;
        // Set first coordinates
        coordinatesArray.push(new Coordinates(y1, x1));
        // Main loop
        while (!((x1 == x2) && (y1 == y2))) {
            var e2 = err << 1;
            if (e2 > -dy) {
                err -= dy;
                x1 += sx;
            }
            if (e2 < dx) {
                err += dx;
                y1 += sy;
            }
            // Set coordinates
            coordinatesArray.push(new Coordinates(y1, x1));
        }
        // Return the result
        return coordinatesArray;
    }
    

提交回复
热议问题