图像没有完全向左移动

时间:2018-04-17 23:25:27

标签: javascript css html5

我试图将图像完全移到左侧。但它并没有向完整的左侧移动。我使用'requestAnimationFrame()'如下。

<!DOCTYPE html>
<html>
    <head>
        <title>Moving Screen Saver</title>
        <style>
            html, body {
                background-image: url("https://s14.postimg.cc/jei3ov2nl/moon_bg.png");
                background-repeat: no-repeat;
            background-size: cover;
                position: relative;
                height: 100%;
                width: 100%;
            }

            .animator {
                width: 100vw;
                height: 100vh;
            }
        </style>
    </head>
    <body>
        <div class="animator"></div>
        <script>

            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'), 'https://s14.postimg.cc/tokio4ne9/mod_cropped.png');
        </script>
    </body>
</html>

即使图像向左移动并重复,也不会完全向左移动。任何人都可以让我知道为什么图像没有完全到达左边。

以下是jsfiddle

https://jsfiddle.net/1zu1bj5h/3/

1 个答案:

答案 0 :(得分:2)

只需添加body { margin: 0; }即可删除body

的默认边距

https://jsfiddle.net/Lyjb190h/1/