How can I draw a single cycle waveform (triangle,saw,) using JS (with phase control)?

I’m trying to generate a single cycle of a waveform, but which can be modified by a phase control. So far I managed to figure out a sine wave like this –

m.move_to(x,y);
for(var i = -w; i < w * 2; i++) {
            
    y = amp * h * 0.5 * Math.sin((i + (phase + 0.5) * w) * ((Math.PI * 2) / w)) + h * 0.5;
            
    m.line_to(x + i,y);
        
}

This is using mgraphics inside max/msp, but it should be clear, just simple code. w and h are the width and height of the box. I started the loop with -w to avoid a line at the start going from the origin x=0,y=0.5 * h.

I tried following the basic logic of this post in order to implement a triangle wave but it ends up starting and ending at y=1, and it doesn’t loop, so when I change the phase I just end up with a lot of blank space.

This is what I have so far for the triangle inside the loop –

y = amp * h * 0.5 * (1 - Math.abs((i + (phase) * w) / w - 0.5) * 4) + h * 0.5;