Can anyone help me optimize this animation I am trying to make.
Basically a car image sits in the foreground and the background moves behind it so it looks like the car is moving. It's pretty simple but it keeps getting very laggy and crashing.
document.addEventListener("fullscreenchange", function() {
console.log('Fullscreen Change');
});
const canvas = document.getElementById("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const ctx = canvas.getContext("2d");
function drawCar(){
ctx.drawImage(img, 20, canvas.height-200);
}
const backgroundFrames = [];
let img;
let interval;
let x = 0;
const patternCanvas = document.createElement('canvas');
const patternContext = patternCanvas.getContext('2d');
patternCanvas.width = 4096;
patternCanvas.height = 700;
const patImg = new Image();
patImg.addEventListener('load', function() {
for (let i = 0; i >= -4096; i -= 16){
patternContext.drawImage(patImg, i, 0);
let k = i/-16;
backgroundFrames[k] = ctx.createPattern(patternCanvas, 'repeat-x');
}
img = new Image();
img.addEventListener('load', function(){
setTimeout(function(){
interval = setInterval(bckchg, 1000/30);
}, 3000);
}, false);
img.src = 'img.png';
}, false);
patImg.src = 'background.jpg';
let l = 0;
function bckchg(){
ctx.fillStyle = backgroundFrames[l];
ctx.fillRect(0, 0, canvas.width, canvas.height);
drawCar();
l++;
if(l === 187){
l = 0;
}
}
canvas.addEventListener('click', function(){
clearInterval(interval);
});
I've tried creating all the background images beforehand but its still pretty laggy and still crashes.
I know the code is pretty messy, I only started coding recently. Any and all help would be appreciated.
Edit:
Here is the HTML
<!doctype html>
<html>
<head>
<title>Drive</title>
<link rel="stylesheet" href="drive1.css">
</head>
<body>
<main>
<canvas id="canvas">
</canvas>
<!--<img src="background.jpg">-->
<!--<div id="menu">-->
<!-- <button id="start">Start</button>-->
<!-- <button id="stop">Stop</button>-->
<!-- <input id="volSlider" type="range" name="vol" min="o" max="100">-->
<!-- <label id="volLabel" for="vol">Volume</label>-->
<!-- <form id="songForm">-->
<!-- <input type="radio" id="td" name="song" value="td">-->
<!-- <label for="td">Tokyo Drift</label>-->
<!-- <br>-->
<!-- <input type="radio" id="supra" name="song" value="supra">-->
<!-- <label for="supra">Supra</label>-->
<!-- </form>-->
<!--</div>-->
</main>
<script src="drive_mk2.js">
</script>
<script src="drive_music.js"></script>
</body>
</html>