To enhance our user experience, we are tasked with creating a captivating screen saver featuring 3 images.
- The bottom image will remain fixed in its position.
- The middle image should move across the screen.
- Lastly, the top image will move at a faster pace compared to the others.
In order to manage these images effectively, we have set up 3 separate divs as outlined below.
<!DOCTYPE html>
<html>
<head>
<title>Moving Screen Saver</title>
<style>
html, body {
position: relative;
height: 100%;
width: 100%;
}
#bgimg {
background-image: url("background/moon_bg.png");
position: absolute;
background-repeat: no-repeat;
background-size: cover;
width: 100%;
height: 100%;
}
.animator {
width: 100vw;
height: 100vh;
}
#poster {
background-image: url("posters/gladiator.png");
position: absolute;
background-position:right 20px bottom 20px;
background-repeat: no-repeat;
width: 100%;
height: 100%;
background-color: transparent;
}
</style>
</head>
<body>
<div id="bgimg"></div>
<div class="animator"></div>
<div id="poster"></div>
<script>
var poster = document.getElementById('poster');
var animate;
function moveRight()
{
poster.style.left = poster.style.left || 0;
poster.style.left = parseInt(poster.style.left) - 10 + 'px';
requestAnimationFrame(moveRight);
}
moveRight();
function rollAnimate(element, url) {
if(!element instanceof HTMLElement)
return;
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var img = new Image();
var x = 0;
var pattern;
var framesPerSec = 10;
img.onload = startDrawing;
img.onerror = console.error;
img.src = url;
canvas.style.cssText = 'position:absolute;'
function startDrawing() {
element.insertBefore(canvas, element.firstChild);
pattern = ctx.createPattern(img, 'repeat');
resize();
anim();
window.addEventListener('resize', resize, {passive: true});
}
function anim() {
x = (x - 1) % img.width;
ctx.setTransform(1,0,0,1,x,(canvas.height) - (img.height));
ctx.fill();
setTimeout(function() {
requestAnimationFrame(anim);
}, 1000 / framesPerSec);
}
function resize(evt) {
canvas.width = element.offsetWidth;
canvas.height = element.offsetHeight;
ctx.fillStyle = pattern;
ctx.rect(0, canvas.height - img.height, canvas.width, img.height);
ctx.globalCompositeOperation = 'copy';
}
}
rollAnimate(document.querySelector('.animator'), 'buildings/mod_cropped.png');
</script>
</body>
</html>
- lower image - bgimg
- middle image - animator
- top image - poster
Currently, the bottom image and the middle image are displaying correctly, but the top image (poster) is not visible. It seems that when attempting to paint the middle image, it is overriding the top image. Can someone offer assistance in resolving this issue?
For reference, here is the corresponding jsfiddle page: