Jump to content

Как вставить анимацию


kirillryder161
 Share

Recommended Posts


Здравствуйте Уважаемые участники форума. Подскажите пожалуйста, как осуществить сие чудо на сайте. 

Есть вот пример:https://codepen.io/rbgray/pen/ZLedpw

Как мне эту анимацию вставить на сайт на все страницы?

Link to comment
Share on other sites

Здравствуйте!
Html запихнуть в Html Например в Html модуль

<div id="large-header" class="large-header">
    <canvas id="demo-canvas"></canvas>
    <div class="main-title">
		<h1>Headline</h1>
		<h4 class="thin">This is a short bit of copy that would take up this space.</h4>
		<a href="/hospitals" class="button">Learn More</a>
	</div>
</div>


Стили можно в файл стилей вложить можно но ненужно в сам Html вставить обернув подобающе

/* Header */
.large-header {
	position: relative;
	width: 100%;
	background: #333;
	overflow: hidden;
	background-size: cover;
	background-position: center center;
	z-index: 1;
}

#large-header {
	background-image: url('https://c1.staticflickr.com/1/728/31670670743_dfec9f137e_z.jpg');
}

.main-title {
	position: absolute;
	margin: 0;
	padding: 0;
	color: #f9f1e9;
	text-align: center;
	top: 50%;
	left: 50%;
	-webkit-transform: translate3d(-50%,-50%,0);
	transform: translate3d(-50%,-50%,0);
}

.demo-1 .main-title {
	text-transform: uppercase;
	font-size: 4.2em;
	letter-spacing: 0.1em;
}

.main-title .thin {
	font-weight: 200;
}


.button {
    display: inline-block;
    vertical-align: middle;
    margin: 0 0 1rem;
    padding: .85em 1em;
    -webkit-appearance: none;
    border: 1px solid transparent;
    border-radius: .1875rem;
    -webkit-transition: background-color .25s ease-out,color .25s ease-out;
    transition: background-color .25s ease-out,color .25s ease-out;
    font-size: .9rem;
    line-height: 1;
    text-align: center;
    cursor: pointer;
    background-color: #ef3829;
    color: #fefefe;
}
.button:hover{
  background-color: #dd2011;
color: #fefefe;
}

@media only screen and (max-width : 768px) {
	.demo-1 .main-title {
		font-size: 3em;
	}
}

 

яваскрипт можно в файл скриптов вложить или вытягивать его отдельно там где надо или можно но ненужно в сам Html вставить обернув подобающе

(function() {

    var width, height, largeHeader, canvas, ctx, points, target, animateHeader = true;

    // Main
    initHeader();
    initAnimation();
    addListeners();

    function initHeader() {
        width = window.innerWidth;
        height = window.innerHeight;
        target = {x: width/2, y: height/2};

        largeHeader = document.getElementById('large-header');
        largeHeader.style.height = height+'px';

        canvas = document.getElementById('demo-canvas');
        canvas.width = width;
        canvas.height = height;
        ctx = canvas.getContext('2d');

        // create points
        points = [];
        for(var x = 0; x < width; x = x + width/20) {
            for(var y = 0; y < height; y = y + height/20) {
                var px = x + Math.random()*width/20;
                var py = y + Math.random()*height/20;
                var p = {x: px, originX: px, y: py, originY: py };
                points.push(p);
            }
        }

        // for each point find the 5 closest points
        for(var i = 0; i < points.length; i++) {
            var closest = [];
            var p1 = points[i];
            for(var j = 0; j < points.length; j++) {
                var p2 = points[j]
                if(!(p1 == p2)) {
                    var placed = false;
                    for(var k = 0; k < 5; k++) {
                        if(!placed) {
                            if(closest[k] == undefined) {
                                closest[k] = p2;
                                placed = true;
                            }
                        }
                    }

                    for(var k = 0; k < 5; k++) {
                        if(!placed) {
                            if(getDistance(p1, p2) < getDistance(p1, closest[k])) {
                                closest[k] = p2;
                                placed = true;
                            }
                        }
                    }
                }
            }
            p1.closest = closest;
        }

        // assign a circle to each point
        for(var i in points) {
            var c = new Circle(points[i], 2+Math.random()*2, 'rgba(255,255,255,0.3)');
            points[i].circle = c;
        }
    }

    // Event handling
    function addListeners() {
        if(!('ontouchstart' in window)) {
            window.addEventListener('mousemove', mouseMove);
        }
        window.addEventListener('scroll', scrollCheck);
        window.addEventListener('resize', resize);
    }

    function mouseMove(e) {
        var posx = posy = 0;
        if (e.pageX || e.pageY) {
            posx = e.pageX;
            posy = e.pageY;
        }
        else if (e.clientX || e.clientY)    {
            posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
            posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
        }
        target.x = posx;
        target.y = posy;
    }

    function scrollCheck() {
        if(document.body.scrollTop > height) animateHeader = false;
        else animateHeader = true;
    }

    function resize() {
        width = window.innerWidth;
        height = window.innerHeight;
        largeHeader.style.height = height+'px';
        canvas.width = width;
        canvas.height = height;
    }

    // animation
    function initAnimation() {
        animate();
        for(var i in points) {
            shiftPoint(points[i]);
        }
    }

    function animate() {
        if(animateHeader) {
            ctx.clearRect(0,0,width,height);
            for(var i in points) {
                // detect points in range
                if(Math.abs(getDistance(target, points[i])) < 4000) {
                    points[i].active = 0.3;
                    points[i].circle.active = 0.6;
                } else if(Math.abs(getDistance(target, points[i])) < 20000) {
                    points[i].active = 0.1;
                    points[i].circle.active = 0.3;
                } else if(Math.abs(getDistance(target, points[i])) < 40000) {
                    points[i].active = 0.02;
                    points[i].circle.active = 0.1;
                } else {
                    points[i].active = 0;
                    points[i].circle.active = 0;
                }

                drawLines(points[i]);
                points[i].circle.draw();
            }
        }
        requestAnimationFrame(animate);
    }

    function shiftPoint(p) {
        TweenLite.to(p, 1+1*Math.random(), {x:p.originX-50+Math.random()*100,
            y: p.originY-50+Math.random()*100, ease:Circ.easeInOut,
            onComplete: function() {
                shiftPoint(p);
            }});
    }

    // Canvas manipulation
    function drawLines(p) {
        if(!p.active) return;
        for(var i in p.closest) {
            ctx.beginPath();
            ctx.moveTo(p.x, p.y);
            ctx.lineTo(p.closest[i].x, p.closest[i].y);
            ctx.strokeStyle = 'rgba(156,217,249,'+ p.active+')';
            ctx.stroke();
        }
    }

    function Circle(pos,rad,color) {
        var _this = this;

        // constructor
        (function() {
            _this.pos = pos || null;
            _this.radius = rad || null;
            _this.color = color || null;
        })();

        this.draw = function() {
            if(!_this.active) return;
            ctx.beginPath();
            ctx.arc(_this.pos.x, _this.pos.y, _this.radius, 0, 2 * Math.PI, false);
            ctx.fillStyle = 'rgba(156,217,249,'+ _this.active+')';
            ctx.fill();
        };
    }

    // Util
    function getDistance(p1, p2) {
        return Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2);
    }
    
})();


 

Link to comment
Share on other sites

Большое спасибо за ответ. Но, как вставить именно анимацию без добавления стелей кнопки и т.д. У меня есть уже готовый сайт, не хочется его портить 

В 04.01.2025 в 22:43, freeworld сказал:

Здравствуйте!
Html запихнуть в Html Например в Html модуль

<div id="large-header" class="large-header">
    <canvas id="demo-canvas"></canvas>
    <div class="main-title">
		<h1>Headline</h1>
		<h4 class="thin">This is a short bit of copy that would take up this space.</h4>
		<a href="/hospitals" class="button">Learn More</a>
	</div>
</div>


Стили можно в файл стилей вложить можно но ненужно в сам Html вставить обернув подобающе

/* Header */
.large-header {
	position: relative;
	width: 100%;
	background: #333;
	overflow: hidden;
	background-size: cover;
	background-position: center center;
	z-index: 1;
}

#large-header {
	background-image: url('https://c1.staticflickr.com/1/728/31670670743_dfec9f137e_z.jpg');
}

.main-title {
	position: absolute;
	margin: 0;
	padding: 0;
	color: #f9f1e9;
	text-align: center;
	top: 50%;
	left: 50%;
	-webkit-transform: translate3d(-50%,-50%,0);
	transform: translate3d(-50%,-50%,0);
}

.demo-1 .main-title {
	text-transform: uppercase;
	font-size: 4.2em;
	letter-spacing: 0.1em;
}

.main-title .thin {
	font-weight: 200;
}


.button {
    display: inline-block;
    vertical-align: middle;
    margin: 0 0 1rem;
    padding: .85em 1em;
    -webkit-appearance: none;
    border: 1px solid transparent;
    border-radius: .1875rem;
    -webkit-transition: background-color .25s ease-out,color .25s ease-out;
    transition: background-color .25s ease-out,color .25s ease-out;
    font-size: .9rem;
    line-height: 1;
    text-align: center;
    cursor: pointer;
    background-color: #ef3829;
    color: #fefefe;
}
.button:hover{
  background-color: #dd2011;
color: #fefefe;
}

@media only screen and (max-width : 768px) {
	.demo-1 .main-title {
		font-size: 3em;
	}
}

 

яваскрипт можно в файл скриптов вложить или вытягивать его отдельно там где надо или можно но ненужно в сам Html вставить обернув подобающе

(function() {

    var width, height, largeHeader, canvas, ctx, points, target, animateHeader = true;

    // Main
    initHeader();
    initAnimation();
    addListeners();

    function initHeader() {
        width = window.innerWidth;
        height = window.innerHeight;
        target = {x: width/2, y: height/2};

        largeHeader = document.getElementById('large-header');
        largeHeader.style.height = height+'px';

        canvas = document.getElementById('demo-canvas');
        canvas.width = width;
        canvas.height = height;
        ctx = canvas.getContext('2d');

        // create points
        points = [];
        for(var x = 0; x < width; x = x + width/20) {
            for(var y = 0; y < height; y = y + height/20) {
                var px = x + Math.random()*width/20;
                var py = y + Math.random()*height/20;
                var p = {x: px, originX: px, y: py, originY: py };
                points.push(p);
            }
        }

        // for each point find the 5 closest points
        for(var i = 0; i < points.length; i++) {
            var closest = [];
            var p1 = points[i];
            for(var j = 0; j < points.length; j++) {
                var p2 = points[j]
                if(!(p1 == p2)) {
                    var placed = false;
                    for(var k = 0; k < 5; k++) {
                        if(!placed) {
                            if(closest[k] == undefined) {
                                closest[k] = p2;
                                placed = true;
                            }
                        }
                    }

                    for(var k = 0; k < 5; k++) {
                        if(!placed) {
                            if(getDistance(p1, p2) < getDistance(p1, closest[k])) {
                                closest[k] = p2;
                                placed = true;
                            }
                        }
                    }
                }
            }
            p1.closest = closest;
        }

        // assign a circle to each point
        for(var i in points) {
            var c = new Circle(points[i], 2+Math.random()*2, 'rgba(255,255,255,0.3)');
            points[i].circle = c;
        }
    }

    // Event handling
    function addListeners() {
        if(!('ontouchstart' in window)) {
            window.addEventListener('mousemove', mouseMove);
        }
        window.addEventListener('scroll', scrollCheck);
        window.addEventListener('resize', resize);
    }

    function mouseMove(e) {
        var posx = posy = 0;
        if (e.pageX || e.pageY) {
            posx = e.pageX;
            posy = e.pageY;
        }
        else if (e.clientX || e.clientY)    {
            posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
            posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
        }
        target.x = posx;
        target.y = posy;
    }

    function scrollCheck() {
        if(document.body.scrollTop > height) animateHeader = false;
        else animateHeader = true;
    }

    function resize() {
        width = window.innerWidth;
        height = window.innerHeight;
        largeHeader.style.height = height+'px';
        canvas.width = width;
        canvas.height = height;
    }

    // animation
    function initAnimation() {
        animate();
        for(var i in points) {
            shiftPoint(points[i]);
        }
    }

    function animate() {
        if(animateHeader) {
            ctx.clearRect(0,0,width,height);
            for(var i in points) {
                // detect points in range
                if(Math.abs(getDistance(target, points[i])) < 4000) {
                    points[i].active = 0.3;
                    points[i].circle.active = 0.6;
                } else if(Math.abs(getDistance(target, points[i])) < 20000) {
                    points[i].active = 0.1;
                    points[i].circle.active = 0.3;
                } else if(Math.abs(getDistance(target, points[i])) < 40000) {
                    points[i].active = 0.02;
                    points[i].circle.active = 0.1;
                } else {
                    points[i].active = 0;
                    points[i].circle.active = 0;
                }

                drawLines(points[i]);
                points[i].circle.draw();
            }
        }
        requestAnimationFrame(animate);
    }

    function shiftPoint(p) {
        TweenLite.to(p, 1+1*Math.random(), {x:p.originX-50+Math.random()*100,
            y: p.originY-50+Math.random()*100, ease:Circ.easeInOut,
            onComplete: function() {
                shiftPoint(p);
            }});
    }

    // Canvas manipulation
    function drawLines(p) {
        if(!p.active) return;
        for(var i in p.closest) {
            ctx.beginPath();
            ctx.moveTo(p.x, p.y);
            ctx.lineTo(p.closest[i].x, p.closest[i].y);
            ctx.strokeStyle = 'rgba(156,217,249,'+ p.active+')';
            ctx.stroke();
        }
    }

    function Circle(pos,rad,color) {
        var _this = this;

        // constructor
        (function() {
            _this.pos = pos || null;
            _this.radius = rad || null;
            _this.color = color || null;
        })();

        this.draw = function() {
            if(!_this.active) return;
            ctx.beginPath();
            ctx.arc(_this.pos.x, _this.pos.y, _this.radius, 0, 2 * Math.PI, false);
            ctx.fillStyle = 'rgba(156,217,249,'+ _this.active+')';
            ctx.fill();
        };
    }

    // Util
    function getDistance(p1, p2) {
        return Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2);
    }
    
})();


 

 

Link to comment
Share on other sites

В 04.01.2025 в 23:54, kirillryder161 сказал:

Большое спасибо за ответ. Но, как вставить именно анимацию без добавления стелей кнопки и т.д. У меня есть уже готовый сайт, не хочется его портить 

 

Тогда надо просто вставить JS

Link to comment
Share on other sites

В 05.01.2025 в 00:06, kirillryder161 сказал:

Я вставляю чисто код js. Результата нет

Возможно потому что библиотека TweenLite не подключена, она есть в коде.

Поробуйте в head добавить

Спойлер

<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.20.3/TweenLite.min.js"></script>

 

Link to comment
Share on other sites

В 05.01.2025 в 00:08, chixx сказал:

Возможно потому что библиотека TweenLite не подключена, она есть в коде.

Поробуйте в head добавить

  Скрыть контент

<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.20.3/TweenLite.min.js"></script>

 

 

Вообще не помогает. У меня стоит фоновое изображение и анимация так и не появляется

Link to comment
Share on other sites

В 05.01.2025 в 00:16, kirillryder161 сказал:

 

Вообще не помогает. У меня стоит фоновое изображение и анимация так и не появляется

Тогда проще наймите кого-нибудь. Там может быть все что угодно, по месту лучше смотреть.

Может фоновое изображение перекрывает, или какие другие элементы. Может быть из-за размеров. Надо смотреть чем задано фоновое изображение и т.д.

Либо пробуйте убрать фоновое изображение, либо анимацию пробуйте делать выше по z-index. Там может и функия то не вызвается правильно.

Т.е. анимация должна появлятся выше фонового изображения.

Edited by chixx
Link to comment
Share on other sites

А к чему это всё в серьезном магазине?

Спойлер
<modification>
    <name>Mouse Animation</name>
    <code>mouse_animation</code>
    <version>1.1</version>
    <author>Tom</author>
    <link>Mouse Animation</link>
    <file path="catalog/view/theme/*/template/common/footer.twig">
        <!-- Вставляем анимационный скрипт перед закрывающим </body> -->
        <operation>
            <search><![CDATA[</body></html>]]></search>
            <add position="before"><![CDATA[
                <style>
                    #mouse-animation {
                        position: fixed;
                        top: 0;
                        left: 0;
                        width: 100%;
                        height: 100%;
                        pointer-events: none; /* Отключаем взаимодействие с элементом */
                        z-index: 9999; /* Максимальный уровень */
                    }
                </style>
                <canvas id="mouse-animation"></canvas>
                <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.20.3/TweenLite.min.js"></script>
                <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.20.3/easing/EasePack.min.js"></script>
                
                <script>
                (function() {
                    var width, height, canvas, ctx, points, target, animateHeader = true;

                    // Main
                    initHeader();
                    initAnimation();
                    addListeners();

                    function initHeader() {
                        width = window.innerWidth;
                        height = window.innerHeight;
                        target = {x: width / 2, y: height / 2};

                        canvas = document.getElementById('mouse-animation');
                        canvas.width = width;
                        canvas.height = height;
                        ctx = canvas.getContext('2d');

                        points = [];
                        for (var x = 0; x < width; x += width / 20) {
                            for (var y = 0; y < height; y += height / 20) {
                                var px = x + Math.random() * width / 20;
                                var py = y + Math.random() * height / 20;
                                var p = {x: px, originX: px, y: py, originY: py};
                                points.push(p);
                            }
                        }

                        points.forEach(function(p1) {
                            var closest = [];
                            points.forEach(function(p2) {
                                if (p1 !== p2) {
                                    closest.push(p2);
                                    closest.sort(function(a, b) {
                                        return getDistance(p1, a) - getDistance(p1, b);
                                    });
                                    closest = closest.slice(0, 5);
                                }
                            });
                            p1.closest = closest;
                        });

                        points.forEach(function(p) {
                            p.circle = new Circle(p, 2 + Math.random() * 2, 'rgba(156,217,249,0.3)');
                        });
                    }

                    function addListeners() {
                        if (!('ontouchstart' in window)) {
                            window.addEventListener('mousemove', mouseMove);
                        }
                        window.addEventListener('resize', resize);
                    }

                    function mouseMove(e) {
                        target.x = e.pageX - window.scrollX;
                        target.y = e.pageY - window.scrollY;
                    }

                    function resize() {
                        width = window.innerWidth;
                        height = window.innerHeight;
                        canvas.width = width;
                        canvas.height = height;
                    }

                    function initAnimation() {
                        animate();
                        points.forEach(function(p) {
                            shiftPoint(p);
                        });
                    }

                    function animate() {
                        ctx.clearRect(0, 0, width, height);
                        points.forEach(function(p) {
                            if (getDistance(target, p) < 4000) {
                                p.active = 0.3;
                                p.circle.active = 0.6;
                            } else if (getDistance(target, p) < 20000) {
                                p.active = 0.1;
                                p.circle.active = 0.3;
                            } else if (getDistance(target, p) < 40000) {
                                p.active = 0.02;
                                p.circle.active = 0.1;
                            } else {
                                p.active = 0;
                                p.circle.active = 0;
                            }

                            drawLines(p);
                            p.circle.draw();
                        });
                        requestAnimationFrame(animate);
                    }

                    function shiftPoint(p) {
                        TweenLite.to(p, 1 + 1 * Math.random(), {
                            x: p.originX - 50 + Math.random() * 100,
                            y: p.originY - 50 + Math.random() * 100,
                            ease: Circ.easeInOut,
                            onComplete: function() {
                                shiftPoint(p);
                            }
                        });
                    }

                    function drawLines(p) {
                        if (!p.active) return;
                        p.closest.forEach(function(p2) {
                            ctx.beginPath();
                            ctx.moveTo(p.x, p.y);
                            ctx.lineTo(p2.x, p2.y);
                            ctx.strokeStyle = 'rgba(156,217,249,' + p.active + ')';
                            ctx.stroke();
                        });
                    }

                    function Circle(pos, rad, color) {
                        var _this = this;
                        (function() {
                            _this.pos = pos || null;
                            _this.radius = rad || null;
                            _this.color = color || null;
                        })();

                        this.draw = function() {
                            if (!_this.active) return;
                            ctx.beginPath();
                            ctx.arc(_this.pos.x, _this.pos.y, _this.radius, 0, 2 * Math.PI, false);
                            ctx.fillStyle = 'rgba(156,217,249,' + _this.active + ')';
                            ctx.fill();
                        };
                    }

                    function getDistance(p1, p2) {
                        return Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2);
                    }

                })();
                </script>
            ]]></add>
        </operation>
    </file>
</modification>

 

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...