0

I'm trying to create my own basic sorting algorithm visualizer. I'm running in to an issue when trying to swap two numbers in an array. As part of the process, I need the swap function to also swap the visual lines on the graph.

I've already written this in Python and I'm trying to rewrite it in javascript. This is a gif of it working as intended in Python: https://i.imgur.com/IVWuZ2o.gifv

My issue is that when I want to swap two values, the original lines are not cleared, and are instead just drawn over with the new lines. This is what it ends up looking like after attempting to shuffle the array:

The array was initially sorted least to greatest, then shuffled

Here's the code:

function eraseLine(a, i) {
    ctx.clearRect(i * lineWidth, height - a[i], lineWidth, a[i]);
}

function swap(a, i, j) {
    // clear the lines already there
    lineWidth = width / a.length;
    ctx.lineWidth = lineWidth;

    eraseLine(a, i);
    eraseLine(a, j);

    // actually swap the values
    var temp = a[i];
    a[i] = a[j];
    a[j] = temp;

    // redraw the new lines
    ctx.strokeStyle = "#FFFFFF";
    ctx.moveTo(i * lineWidth + lineWidth / 2, height);
    ctx.lineTo(i * lineWidth + lineWidth / 2, height - a[i]);
    ctx.stroke();

    ctx.moveTo(j * lineWidth + lineWidth / 2, height);
    ctx.lineTo(j * lineWidth + lineWidth / 2, height - a[j]);
    ctx.stroke();
}

async function eraseLines(a, start, end) {
    for(var i = start; i < end; i++) {
        eraseLine(a, i);
        await sleep(50);
    }
}

async function shuffle(a) {
    for(var i = a.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        swap(a, i, j);
        await sleep(50);
    }
}
  • if you have to clear everything from canvas you can call ctx.clearRect(0, 0, canvas.width, canvas.height); – Narendra Oct 13 '18 at 02:18
  • I don't want to do that for performance reasons. If I did, I would have to redraw all the other lines that aren't affected by the swap – Nick Spencer Oct 13 '18 at 02:44
  • Clearing only part of the context will incur about the same perf drawback as redrawing everything. Clear all and redraw, always. – Kaiido Oct 13 '18 at 07:44

1 Answers1

0

I fixed it by adding ctx.beginPath() before starting to draw a line and ctx.closePath(). I thought that stroke() would handle this for me.