This is a follow-up on the post about Triangular Grids, to see how easily we could adapt a regular grid for the Marching Squares Algorithm.
Rectangular Grid
As is custom, I'll start with the Marching Squares Algorithm, explained so beautifully on Wikipedia. We start with a grid which samples some continuous function (illustrated with colored circles here). For each square we then draw from zero to two line segments connecting the edges, based on whether the corners are above-or-below the threshold value (an interactive slider at the bottom), then interpolating where along the edge the threshold would theoretically be hit. The end goal is to determine the curves that plot out the contour at which the function takes the threshold value. Here we draw 30x15 squares.
As should be obvious, the function is only sampled at the corners of the grid cells (and occasionally at the midpoint for the saddle edge-case, which is not displayed above), so the curve suffers from aliasing artifacts. To correct for this, we can always make the grid a lot finer. Let's take the same grid, but render it with 300x150 squares. Moving the threshold slider now feels a lot slower, since we have to recompute curve segments at each of the 45k squares at each increment, which takes a while. Critically, I don't render the individual squares and their component curves as individual SVG elements, since that puts too much strain on the browser. Instead, I join the curve segments by each square together in one megacurve. This saves a lot on DOM-rendering overhead.