So you may have seen my XNA - Scrolling Background or the GDI+ version, well here is the JavaScript version:
HTML Code:
<!DOCTYPE html>
<html>
<head>
<title>Infinite Scroller Game</title>
<style>
canvas {
border: 1px solid #000;
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="800" height="400"></canvas>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.src = 'https://www.vbforums.com/attachment.php?attachmentid=113103&d=1398112502'; // this is the attachment used below
let x = 0;
function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBackground();
update();
window.requestAnimationFrame(gameLoop);
}
function drawBackground() {
ctx.drawImage(img, x, 0, canvas.width, canvas.height);
ctx.drawImage(img, x + canvas.width, 0, canvas.width, canvas.height);
}
function update() {
x -= 1;
if (x <= -canvas.width) {
x = 0;
}
}
window.addEventListener('load', () => {
// Start the game loop
gameLoop();
}, false);
</script>
</body>
</html>
Example: https://jsfiddle.net/8gz0v7wp