How to add a texture that follows the movement?

I would like to move my landscape to simulate a world moving on the x-axis. I use createPattern() to add an image inside my path, but the pattern draws the image at the same position when the path is moving: the top of the "mountains" (the lines) move to the left, but the image stays where it is below the lines.

I generate some coordinates in an array, I draw a line between them and I add an offset with a setInterval. After each iteration, the position of each point is modified by the offset :

let path = 'M'+(points[i-1].x - offsetX)+' '+points[i-1].y;
path += 'L'+(points[i].x - offsetX)+' '+points[i].y;
//etc.


How could I add a texture that follows the movement?

You can see that the pattern is repeated even though the mountains have moved to the left :

edit :

The code :

function draw(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.translate(-moveX, 0);
for (let i=Math.max(fromKeyPoint, 1); i<toKeyPoint; ++i){
ctx.beginPath();

ctx.lineCap = 'round';
ctx.lineWidth = size;
ctx.strokeStyle = color;
ctx.moveTo(points[i-1].x, points[i-1].y);

ctx.lineTo(points[i].x, points[i].y);
ctx.stroke();

let path = 'M'+(points[i-1].x)+' '+points[i-1].y;
path += 'L'+(points[i].x)+' '+points[i].y;
path += 'L'+(points[i].x)+' '+canvas.height;
path += 'L'+(points[i-1].x)+' '+canvas.height;
path += 'Z';
let p = new Path2D(path);
console.log("path : "+path);

ctx.fillStyle = ctx.createPattern(imgTexture, "repeat");
ctx.fill(p);
}

• Instead of adding an offset to each x position, have you considered shifting the whole drawing context with context.translate? Feb 8, 2022 at 21:50
• nice @DMGregory thank you very much Feb 8, 2022 at 22:09
• If that solved your problem, try sharing your revised code as an answer below. Feb 8, 2022 at 22:10
• @DMGregory actually there is an issue, when the new points from the right arrive in the viewport, I edited the post with an image, I did not have this when I added the offset to the coordinates, so I don't think it's an issue with the generated coordinates. Feb 8, 2022 at 22:19
• Are you clearing your canvas before drawing the next frame? And is your clearing rectangle correctly covering the entire canvas? (ie. either undoing or compensating for the shift in the coordinate system when choosing the area to clear) Feb 8, 2022 at 23:11

ctx.clearRect(points[fromKeyPoint].x, 0, points[toKeyPoint].x, canvas.height);

and use ctx.translate(-moveX, 0); to move the mountains.