This is driving me crazy. I found some interesting JS image panning code from the internet. It works wonderfully, but the image begins to pan on a button click event, and I would like it to start panning automatically once the page has loaded.
I can see the canvas element loads followed by the button on lines 12 and 14. I can also see that the script that passes the function startStop() to btnStart on line 37. I have played extensively with this, but for the life of me I cannot separate the button click event from the rest of the script so that the entire function can be started automatically. I'm not much of a JS programmer. Any help would be hugely appreciated. After nine hours I'm beaten by this. Many thanks in advance - Peter
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>The problem</title>
<meta name="viewport" content="width=device-width">
<meta name="robots" content="noindex,follow">
<link rel="stylesheet" href="style01.css" />
</head>
<body>
<div>
<canvas id="bg" width="440" height="220"></canvas>
<br /><br />
<button id="btnStart" class="btn btn-default">Start/stop animation</button>
</div>
<script>
(function() {
window.requestAnimationFrame = window.requestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.mozRequestAnimationFrame
|| function(callback) { window.setTimeout(callback, 1000 / 60); };
var canvas = document.getElementById('bg');
var context = canvas.getContext('2d');
var looping = false;
var totalSeconds = 0;
var img = new Image();
img.onload = imageLoaded;
img.src = '/img/bg01.jpg';
function imageLoaded() {
draw(0);
var btn = document.getElementById('btnStart');
btn.addEventListener('click', function() {
startStop();
});
}
var lastFrameTime = 0;
function startStop() {
looping = !looping;
if (looping) {
lastFrameTime = Date.now();
requestAnimationFrame(loop);
}
}
function loop() {
if (!looping) {
return;
}
requestAnimationFrame(loop);
var now = Date.now();
var deltaSeconds = (now - lastFrameTime) / 5000;
lastFrameTime = now;
draw(deltaSeconds);
}
function draw(delta) {
totalSeconds += delta;
var x = -1 * (img.width - canvas.width) / 2 * (1 + Math.cos(totalSeconds / Math.PI));
var y = -1 * (img.height - canvas.height) / 2 * (1 + -Math.sin(totalSeconds / Math.PI));
context.drawImage(img, x, y);
}
}());
</script>
</body>
</html>
This seems very simple, however it's made hard by the lack of indentation in the code. I suggest you add some tabs to this script to make it easier to read.
As for the problem, all you have to do is to remove the addition of the event in the button, and instead just run the function right. So in this part:
var btn = document.getElementById('btnStart');
btn.addEventListener('click', function() {
startStop();
});
Replace it by this only:
startStop();
After that, you can remove the button from the HTML entirely.