Tracing two paths at the same time on an HTML5 canvas
<p>I have code that is spiritually equivalent to this snippet:</p>

<pre><code>function drawComplicatedThing(ctx) {
    let [px, py] = [0, 0];
    for (let i = 0; i &lt; 10000; i++) {
        let {x, y} = computeExpensive(i);

        // black along
        ctx.beginPath();
        ctx.moveTo(px, py);
        ctx.lineTo(x, y);
        ctx.strokeStyle = 'black';
        ctx.stroke();

        // red transpose
        ctx.beginPath();
        ctx.moveTo(py, px);
        ctx.lineTo(y, x);
        ctx.strokeStyle = 'red';
        ctx.stroke();

        [px, py] = [x, y];
    }
}
</code></pre>

<p>I'm trying to optimize the code by batching the calls to stroke. For example, I could do this:</p>

<pre><code>function drawComplicatedThing(ctx) {
    // black along
    ctx.moveTo(0, 0);
    for (let i = 0; i &lt; 10000; i++) {
        let {x, y} = computeExpensive(i);
        ctx.lineTo(x, y);
    }
    ctx.strokeStyle = 'black';
    ctx.stroke();

    // red transpose
    ctx.moveTo(0, 0);
    for (let i = 0; i &lt; 10000; i++) {
        let {x, y} = computeExpensive(i);
        ctx.lineTo(y, x);
    }
    ctx.strokeStyle = 'red';
    ctx.stroke();
}
</code></pre>

<p>But notice that now I'm calling <code>computeExpensive</code> twice as many times. This is slower, but the real cost is that in practice <code>computeExpensive</code> is actually an inline block of code, so our optimization has forced gross code duplication.</p>

<p>Restructuring the example code to avoid the code duplication is easy (just cache the points into an array), but in general there may be conditional drawing logic and that's a lot harder to restructure away when duplicated.</p>

<p>It would be easy to workaround this issue if I could trace two paths at the same time. Something like this:</p>

<pre><code>function drawComplicatedThing(ctx) {
    let ctx2 = ctx.independentCopy(); // &lt;-- NOT REAL, but you get the idea
    ctx.moveTo(0, 0);
    ctx2.moveTo(0, 0);
    for (let i = 0; i &lt; 10000; i++) {
        let {x, y} = computeExpensive(i);
        ctx.lineTo(x, y);
        ctx2.lineTo(y, x);
    }
    ctx.strokeStyle = 'black';
    ctx.stroke();
    ctx2.strokeStyle = 'red';
    ctx2.stroke();
}
</code></pre>

<p>Does this kind of functionality exist in HTML5, or am I required to structure my code around only being able to trace one path-to-stroke at a time?</p>