JavaScript - Page Has to Be Refreshed to Show Particle-Slider Logo Effect

JavaScript - page has to be refreshed to show particle-slider logo effect

tl;dr

replace this code:

<script type="text/javascript">
var ps = new ParticleSlider({ 'width':'1400', 'height': '600' });
</script>

with this code:

<script type="text/javascript">
//wait until the DOM is ready to be queried
document.addEventListener('DOMContentLoaded', function() { //DOM-ready callback
var ps, timeout;
handlePS();
window.addEventListener('resize', function() {
if (timeout) { //check if the timer has been set
clearTimeout(timeout); //clear the timer
}
//set a timer
timeout = setTimeout(handlePS, 250);
});

function handlePS() {
if (document.body.clientWidth >= 960) {
//check if ps is assigned as an instance of the ParticleSlider
if (window.ps && typeof ps !== null) {
ps.init(); //refresh the particle slider since it exists
} else {
//otherwise create a new instance of the particle slider
ps = new ParticleSlider({
'width': '1400',
'height': '600'
});
}
}
else {
//when the flat logo is displayed, get rid of the particle slider instance
ps = null;
}
}
});
</script>

Explanation: Call init() on resize

One can add a callback for when the resize event occurs (as others have mentioned) and call the init() method depending on the current width of the window.

It might be advisable to move the code that creates the Particle Slider instance
to a function, which checks if the width of the window is greater than or equal to 960 pixels (using .clientWidth of document.body) and if so, if the instance has been created or not using a variable ps declared outside the function. If the instance has been created, call the init method; Otherwise create the instance. But if the width is less than 960 pixels then set the variable ps to null.

var ps; //declare out here for use in multiple functions
function handlePS() {
if (document.body.clientWidth > 960) {
if (window.ps && typeof ps !== null) {
ps.init();
} else {
ps = new ParticleSlider({'width': '1400', 'height': '600'});
}
}
else {
ps = null;
}
}

Then that function can be called when the page loads as well as when the resize event occurs:

handlePS();
window.addEventListener('resize', handlePS);

See a demonstration in this sample page. There are a few other enhancements added:

  • it waits for the DOM to be ready by calling handlePS() and listening for the resize event after the DOMContentLoaded event has been fired by using document.addEventListener
  • it uses setTimeout for a debounce effect so that the init() method is called 250ms after the scroll event ends instead of continuously during a scroll event.

So the code with those enhancements looks like below:

//wait until the DOM is ready to be queried
document.addEventListener('DOMContentLoaded', function() { //DOM-ready callback
var ps, timeout;
handlePS();
window.addEventListener('resize', function() {
//https://davidwalsh.name/javascript-debounce-function
if (timeout) { //check if the timer has been set
clearTimeout(timeout); //clear the timer
}
//set a timer
timeout = setTimeout(handlePS, 250);
});

function handlePS() {
if (document.body.clientWidth >= 960) {
//check if ps is assigned as an instance of the ParticleSlider
if (window.ps && typeof ps !== null) {
ps.init(); //refresh the particle slider since it exists
} else {
//otherwise create a new instance of the particle slider
ps = new ParticleSlider({
'width': '1400',
'height': '600'
});
}
}
else {
//when the flat logo is displayed, get rid of the particle slider instance
ps = null;
}
}
});

And because you added the jquery tag, jQuery could be used to simplify things a bit:

instead of

window.addEventListener('resize', handlePS);

use:

$(window).on('resize, handlePS);

And replace document.body.clientWidth width $(document).width().

Update

I used the image from your comment in the updated sample page. I also pared down the code used on the Particle Slider demo page and added in that image on this demo page. It still suffers from flashing when there is a resize.

How to remove loading effect in particle slider?

function ParticleSlider(a) {    var b = this;    b.sliderId = "particle-slider", b.color = "#fff", b.hoverColor = "#88f", b.width = 0, b.height = 20, b.ptlGap = 0, b.ptlSize = 1, b.slideDelay = 10, b.arrowPadding = 10, b.showArrowControls = !0, b.onNextSlide = null, b.onWidthChange = null, b.onHeightChange = null, b.onSizeChange = null, b.monochrome = !1, b.mouseForce = 1e4, b.restless = !0, b.imgs = [];    if (a) {        var c = ["color", "hoverColor", "width", "height", "ptlGap", "ptlSize", "slideDelay", "arrowPadding", "sliderId", "showArrowControls", "onNextSlide", "monochrome", "mouseForce", "restless", "imgs", "onSizeChange", "onWidthChange", "onHeightChange"];        for (var d = 0, e = c.length; d < e; d++) a[c[d]] && (b[c[d]] = a[c[d]])    }    b.$container = b.$("#" + b.sliderId), b.$$children = b.$container.childNodes, b.$controlsContainer = b.$(".controls"), b.$$slides = b.$(".slide", b.$(".slides").childNodes, !0), b.$controlLeft = null, b.$controlRight = null, b.$canv = b.$(".draw"), b.$srcCanv = document.createElement("canvas"), b.$srcCanv.style.display = "none", b.$container.appendChild(b.$srcCanv), b.$prevCanv = document.createElement("canvas"), b.$prevCanv.style.display = "none", b.$container.appendChild(b.$prevCanv), b.$nextCanv = document.createElement("canvas"), b.$nextCanv.style.display = "none", b.$container.appendChild(b.$nextCanv), b.$overlay = document.createElement("p"), b.$container.appendChild(b.$overlay), b.imgControlPrev = null, b.imgControlNext = null, b.$$slides.length <= 1 && (b.showArrowControls = !1), b.$controlsContainer && b.$controlsContainer.childNodes && b.showArrowControls == !0 ? (b.$controlLeft = b.$(".left", b.$controlsContainer.childNodes), b.$controlRight = b.$(".right", b.$controlsContainer.childNodes), b.imgControlPrev = new Image, b.imgControlNext = new Image, b.imgControlPrev.onload = function () {        b.$prevCanv.height = this.height, b.$prevCanv.width = this.width, b.loadingStep()    },        b.imgControlNext.onload = function () {            b.$nextCanv.height = this.height, b.$nextCanv.width = this.width, b.loadingStep()        },        b.imgControlPrev.src = b.$controlLeft.getAttribute("data-src"), b.imgControlNext.src = b.$controlRight.getAttribute("data-src")) : b.showArrowControls = !1, b.width <= 0 && (b.width = b.$container.clientWidth), b.height <= 0 && (b.height = b.$container.clientHeight), b.mouseDownRegion = 0, b.colorArr = b.parseColor(b.color), b.hoverColorArr = b.parseColor(b.hoverColor), b.mx = -1, b.my = -1, b.swipeOffset = 0, b.cw = b.getCw(), b.ch = b.getCh(), b.frame = 0, b.nextSlideTimer = !1, b.currImg = 0, b.lastImg = 0, b.imagesLoaded = 0, b.pxlBuffer = {            first: null        },        b.recycleBuffer = {            first: null        }, b.ctx = b.$canv.getContext("2d"), b.srcCtx = b.$srcCanv.getContext("2d"), b.prevCtx = b.$prevCanv.getContext("2d"), b.nextCtx = b.$nextCanv.getContext("2d"), b.$canv.width = b.cw, b.$canv.height = b.ch, b.shuffle = function () {            var a, b;            for (var c = 0, d = this.length; c < d; c++) b = Math.floor(Math.random() * d), a = this[c], this[c] = this[b], this[b] = a        }, Array.prototype.shuffle = b.shuffle, b.$canv.onmouseout = function () {            b.mx = -1, b.my = -1, b.mouseDownRegion = 0        }, b.$canv.onmousemove = function (a) {            function c(a) {                var c = 0,                    d = 0,                    e = typeof a == "string" ? b.$(a) : a;                if (e) {                    c = e.offsetLeft, d = e.offsetTop;                    var f = document.getElementsByTagName("body")[0];                    while (e.offsetParent && e != f) c += e.offsetParent.offsetLeft, d += e.offsetParent.offsetTop, e = e.offsetParent                }                this.x = c, this.y = d            }            var d = new c(b.$container);            b.mx = a.clientX - d.x + document.body.scrollLeft + document.documentElement.scrollLeft, b.my = a.clientY - d.y + document.body.scrollTop + document.documentElement.scrollTop        }, b.$canv.onmousedown = function () {            if (b.imgs.length > 1) {                var a = 0;                b.mx >= 0 && b.mx < b.arrowPadding * 2 + b.$prevCanv.width ? a = -1 : b.mx > 0 && b.mx > b.cw - (b.arrowPadding * 2 + b.$nextCanv.width) && (a = 1), b.mouseDownRegion = a            }        }, b.$canv.onmouseup = function () {            if (b.imgs.length > 1) {                var a = "";                b.mx >= 0 && b.mx < b.arrowPadding * 2 + b.$prevCanv.width ? a = -1 : b.mx > 0 && b.mx > b.cw - (b.arrowPadding * 2 + b.$nextCanv.width) && (a = 1), a != 0 && b.mouseDownRegion != 0 && (a != b.mouseDownRegion && (a *= -1), b.nextSlideTimer && clearTimeout(b.nextSlideTimer), b.nextSlide(a)), b.mouseDownRegion = 0            }        };    if (b.imgs.length == 0)        for (var d = 0, e = b.$$slides.length; d < e; d++) {            var f = new Image;            b.imgs.push(f), f.src = b.$$slides[d].getAttribute("data-src")        }    b.imgs.length > 0 && (b.imgs[0].onload = function () {        b.loadingStep()    }), b.requestAnimationFrame(function () {        b.nextFrame()    })}var psParticle = function (a) {    this.ps = a, this.ttl = null, this.color = a.colorArr, this.next = null, this.prev = null, this.gravityX = 0, this.gravityY = 0, this.x = 0, this.y = 0, this.velocityX = 0, this.velocityY = 0};psParticle.prototype.move = function () {    var a = this.ps,        b = this;    if (this.ttl != null && this.ttl-- <= 0) a.swapList(b, a.pxlBuffer, a.recycleBuffer), this.ttl = null;    else {        var c = this.gravityX + a.swipeOffset - this.x,            d = this.gravityY - this.y,            e = Math.sqrt(Math.pow(c, 2) + Math.pow(d, 2)),            f = Math.atan2(d, c),            g = e * .01;        a.restless == !0 ? g = 0 : (this.x = this.gravityX - 60, this.y = this.gravityY);        var h = 0,            i = 0;        if (a.mx >= 0 && a.mouseForce) {            var j = this.x - a.mx,                k = this.y - a.my;            h = Math.min(a.mouseForce / (Math.pow(j, 2) + Math.pow(k, 2)), a.mouseForce), i = Math.atan2(k, j), typeof this.color == "function" && (i += Math.PI, h *= .001 + Math.random() * .1 - .05)        } else h = 0, i = 0;        this.velocityX += g * Math.cos(f) + h * Math.cos(i), this.velocityY += g * Math.sin(f) + h * Math.sin(i), this.velocityX *= .92, this.velocityY *= .92, this.x += this.velocityX, this.y += this.velocityY    }}, ParticleSlider.prototype.Particle = psParticle, ParticleSlider.prototype.swapList = function (a, b, c) {    var d = this;    a == null ? a = new d.Particle(d) : b.first == a ? a.next != null ? (a.next.prev = null, b.first = a.next) : b.first = null : a.next == null ? a.prev.next = null : (a.prev.next = a.next, a.next.prev = a.prev), c.first == null ? (c.first = a, a.prev = null, a.next = null) : (a.next = c.first, c.first.prev = a, c.first = a, a.prev = null)}, ParticleSlider.prototype.parseColor = function (a) {    var b, a = a.replace(" ", "");    if (b = /^#([\da-fA-F]{2})([\da-fA-F]{2})([\da-fA-F]{2})/.exec(a)) b = [parseInt(b[1], 16), parseInt(b[2], 16), parseInt(b[3], 16)];    else if (b = /^#([\da-fA-F])([\da-fA-F])([\da-fA-F])/.exec(a)) b = [parseInt(b[1], 16) * 17, parseInt(b[2], 16) * 17, parseInt(b[3], 16) * 17];    else if (b = /^rgba\(([\d]+),([\d]+),([\d]+),([\d]+|[\d]*.[\d]+)\)/.exec(a)) b = [+b[1], +b[2], +b[3], +b[4]];    else if (b = /^rgb\(([\d]+),([\d]+),([\d]+)\)/.exec(a)) b = [+b[1], +b[2], +b[3]];    else return null;    isNaN(b[3]) && (b[3] = 1), b[3] *= 255;    return b}, ParticleSlider.prototype.loadingStep = function () {    var a = this;    a.imagesLoaded++;    if (a.imagesLoaded >= 3 || a.showArrowControls == !1) a.resize(), a.slideDelay > 0 && (a.nextSlideTimer = setTimeout(function () {        a.nextSlide()    }, 1e3 * a.slideDelay))}, ParticleSlider.prototype.$ = function (a, b, c) {    var d = this;    if (a[0] == ".") {        var e = a.substr(1);        b || (b = d.$$children);        var f = [];        for (var g = 0, h = b.length; g < h; g++) b[g].className && b[g].className == e && f.push(b[g]);        return f.length == 0 ? null : f.length == 1 && !c ? f[0] : f    }    return document.getElementById(a.substr(1))}, ParticleSlider.prototype.nextFrame = function () {    var a = this;    a.mouseDownRegion == 1 && a.mx < a.cw / 2 || a.mouseDownRegion == -1 && a.mx > a.cw / 2 ? a.swipeOffset = a.mx - a.cw / 2 : a.swipeOffset = 0;    var b = a.pxlBuffer.first,        c = null;    while (b != null) c = b.next, b.move(), b = c;    a.drawParticles();    if (a.frame++ % 25 == 0 && (a.cw != a.getCw() || a.ch != a.getCh())) {        var d = a.getCh(),            e = a.getCw();        a.ch != e && typeof a.onWidthChange == "function" && a.onWidthChange(a, e), a.ch != d && typeof a.onHeightChange == "function" && a.onHeightChange(a, d), typeof a.onSizeChange == "function" && a.onSizeChange(a, e, d), a.resize()    }    setTimeout(function () {        a.requestAnimationFrame(function () {            a.nextFrame()        })    }, 15)}, ParticleSlider.prototype.nextSlide = function (a) {    var b = this;    b.nextSlideTimer != null && b.imgs.length > 1 ? (b.currImg = (b.currImg + b.imgs.length + (a ? a : 1)) % b.imgs.length, b.resize(), b.slideDelay > 0 && (b.nextSlideTimer = setTimeout(function () {        b.nextSlide()    }, 1e3 * b.slideDelay))) : b.slideDelay > 0 && (b.nextSlideTimer = setTimeout(function () {        b.nextSlide()    }, 1e3 * b.slideDelay)), typeof b.onNextSlide == "function" && b.onNextSlide(b.currImg)}, ParticleSlider.prototype.drawParticles = function () {    var a = this,        b = a.ctx.createImageData(a.cw, a.ch),        c = b.data,        d, e, f, g, h, i, j = a.pxlBuffer.first;    while (j != null) {        e = ~~j.x, f = ~~j.y;        for (g = e; g < e + a.ptlSize && g >= 0 && g < a.cw; g++)            for (h = f; h < f + a.ptlSize && h >= 0 && h < a.ch; h++) d = (h * b.width + g) * 4, i = typeof j.color == "function" ? j.color() : j.color, c[d + 0] = i[0], c[d + 1] = i[1], c[d + 2] = i[2], c[d + 3] = i[3];        j = j.next    }    b.data = c, a.ctx.putImageData(b, 0, 0)}, ParticleSlider.prototype.getPixelFromImageData = function (a, b, c) {    var d = this,        e = [];    for (var f = 0; f < a.width; f += d.ptlGap + 1)        for (var g = 0; g < a.height; g += d.ptlGap + 1) i = (g * a.width + f) * 4, a.data[i + 3] > 0 && e.push({            x: b + f,            y: c + g,            color: d.monochrome == !0 ? [d.colorArr[0], d.colorArr[1], d.colorArr[2], d.colorArr[3]] : [a.data[i], a.data[i + 1], a.data[i + 2], a.data[i + 3]]        });    return e}, ParticleSlider.prototype.init = function (a) {    var b = this;    if (b.imgs.length > 0) {        b.$srcCanv.width = b.imgs[b.currImg].width, b.$srcCanv.height = b.imgs[b.currImg].height, b.srcCtx.clearRect(0, 0, b.$srcCanv.width, b.$srcCanv.height), b.srcCtx.drawImage(b.imgs[b.currImg], 0, 0);        var c = b.getPixelFromImageData(b.srcCtx.getImageData(0, 0, b.$srcCanv.width, b.$srcCanv.height), ~~(b.cw / 2 - b.$srcCanv.width / 2), ~~(b.ch / 2 - b.$srcCanv.height / 2));        if (b.showArrowControls == !0) {            b.prevCtx.clearRect(0, 0, b.$prevCanv.width, b.$prevCanv.height), b.prevCtx.drawImage(b.imgControlPrev, 0, 0);            var d = b.getPixelFromImageData(b.prevCtx.getImageData(0, 0, b.$prevCanv.width, b.$prevCanv.height), b.arrowPadding, ~~(b.ch / 2 - b.$prevCanv.height / 2));            for (var e = 0, f = d.length; e < f; e++) d[e].color = function () {                return b.mx >= 0 && b.mx < b.arrowPadding * 2 + b.$prevCanv.width ? b.hoverColorArr : b.colorArr            }, c.push(d[e]);            b.nextCtx.clearRect(0, 0, b.$nextCanv.width, b.$nextCanv.height), b.nextCtx.drawImage(b.imgControlNext, 0, 0);            var g = b.getPixelFromImageData(b.nextCtx.getImageData(0, 0, b.$nextCanv.width, b.$nextCanv.height), b.cw - b.arrowPadding - b.$nextCanv.width, ~~(b.ch / 2 - b.$nextCanv.height / 2));            for (var e = 0, f = g.length; e < f; e++) g[e].color = function () {                return b.mx > 0 && b.mx > b.cw - (b.arrowPadding * 2 + b.$nextCanv.width) ? b.hoverColorArr : b.colorArr            }, c.push(g[e])        }        if (b.currImg != b.lastImg || a == !0) c.shuffle(), b.lastImg = b.currImg;        var h = b.pxlBuffer.first;        for (var e = 0, f = c.length; e < f; e++) {            var i = null;            h != null ? (i = h, h = h.next) : (b.swapList(b.recycleBuffer.first, b.recycleBuffer, b.pxlBuffer), i = b.pxlBuffer.first), i.gravityX = c[e].x, i.gravityY = c[e].y, i.color = c[e].color        }        while (h != null) h.ttl = ~~(Math.random() * 10), h.gravityY = ~~(b.ch * Math.random()), h.gravityX = ~~(b.cw * Math.random()), h = h.next;        b.$overlay.innerHTML = b.$$slides[b.currImg].innerHTML    }}, ParticleSlider.prototype.getCw = function () {    var a = this;    return Math.min(document.body.clientWidth, a.width, a.$container.clientWidth)}, ParticleSlider.prototype.getCh = function () {    var a = this;    return Math.min(document.body.clientHeight, a.height, a.$container.clientHeight)}, ParticleSlider.prototype.resize = function () {    var a = this;    a.cw = a.getCw(), a.ch = a.getCh(), a.$canv.width = a.cw, a.$canv.height = a.ch, a.init(!0)}, ParticleSlider.prototype.setColor = function (a) {    var b = this;    b.colorArr = b.parseColor(a)}, ParticleSlider.prototype.setHoverColor = function (a) {    var b = this;    b.hoverColorArr = b.parseColor(a)}, ParticleSlider.prototype.requestAnimationFrame = function (a) {    var b = this,        c = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (a) {            window.setTimeout(a, 1e3 / 60)        };    c(a)};

Random Multiple image rotator - display a screen of images randomly when page refreshed?

Just use some random numbers to move the elements around.

Javascript's Math.random will do fine for this, then iterate over all the images and move them around a bit on page load.

Here's a really simple example:

$('.images').each(function() {
randomElm = $('.images').get(Math.floor(Math.random()*10));
randomElm.parentNode.insertBefore(this, randomElm);
});

Here's a FIDDLE

How to hide particle effect (Circles) until .png that it animates is loaded?

You can remove/comment out these lines:

    this.context.beginPath();
this.context.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false);
this.context.fillStyle = "rgba(0, 255, 255, 1)";
this.context.fill();
this.context.closePath();

This essentially draws a single circle.

HTML Canvas performance on resize

Most important boost you get from clearing the requestAnimationFrame:

var rafID = null; //scoping requestAnimationFrame request-ID
//...
//inside resize-callback
window.cancelAnimationFrame(rafID);
...
//inside init() + inside render()
rafID = window.requestAnimationFrame(render);

In this way, we make sure that the browser is not still trying to update the old instances. I added it to the code snippet bellow, where I also made sure that the timeout works (for debouncing).

(function(f,e){"object"===typeof exports&&"undefined"!==typeof module?module.exports=e():"function"===typeof define&&define.amd?define(e):f.Stats=e()})(this,function(){var f=function(){function e(a){c.appendChild(a.dom);return a}function u(a){for(var d=0;d<c.children.length;d++)c.children[d].style.display=d===a?"block":"none";l=a}var l=0,c=document.createElement("div");c.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000";c.addEventListener("click",function(a){a.preventDefault();u(++l%c.children.length)},!1);var k=(performance||Date).now(),g=k,a=0,r=e(new f.Panel("FPS","#0ff","#002")),h=e(new f.Panel("MS","#0f0","#020"));if(self.performance&&self.performance.memory)var t=e(new f.Panel("MB","#f08","#201"));u(0);return{REVISION:16,dom:c,addPanel:e,showPanel:u,begin:function(){k=(performance||Date).now()},end:function(){a++;var c=(performance||Date).now();h.update(c-k,200);if(c>g+1E3&&(r.update(1E3*a/(c-g),100),g=c,a=0,t)){var d=performance.memory;t.update(d.usedJSHeapSize/1048576,d.jsHeapSizeLimit/1048576)}return c},update:function(){k=this.end()},domElement:c,setMode:u}};f.Panel=function(e,f,l){var c=Infinity,k=0,g=Math.round,a=g(window.devicePixelRatio||1),r=80*a,h=48*a,t=3*a,v=2*a,d=3*a,m=15*a,n=74*a,p=30*a,q=document.createElement("canvas");q.width=r;q.height=h;q.style.cssText="width:80px;height:48px";var b=q.getContext("2d");b.font="bold "+9*a+"px Helvetica,Arial,sans-serif";b.textBaseline="top";b.fillStyle=l;b.fillRect(0,0,r,h);b.fillStyle=f;b.fillText(e,t,v);b.fillRect(d,m,n,p);b.fillStyle=l;b.globalAlpha=.9;b.fillRect(d,m,n,p);return{dom:q,update:function(h,w){c=Math.min(c,h);k=Math.max(k,h);b.fillStyle=l;b.globalAlpha=1;b.fillRect(0,0,r,m);b.fillStyle=f;b.fillText(g(h)+" "+e+" ("+g(c)+"-"+g(k)+")",t,v);b.drawImage(q,d+a,m,n-a,p,d,m,n-a,p);b.fillRect(d+n-a,m,a,p);b.fillStyle=l;b.globalAlpha=.9;b.fillRect(d+n-a,m,a,g((1-h/w)*p))}}};return f});
var canvas = document.getElementById("inner_heading-canvas");
var timeoutID = null; var rafID = null;
if (canvas.getContext) { var context = canvas.getContext("2d");}
window.addEventListener("load", init, false);window.addEventListener( "resize", function() { clearTimeout(timeoutID); window.cancelAnimationFrame(rafID); timeoutID = setTimeout(init, 500); }, false);
// Initfunction init() { var net = undefined;
canvas.width = window.innerWidth; canvas.height = window.innerHeight;
var nodesLength = Math.floor(canvas.width * canvas.height / 2000);
// Nodes net = new Net(); net.populate(nodesLength);
rafID = window.requestAnimationFrame(render);
function render() { net.update(); net.draw(); net.connect(50); rafID = window.requestAnimationFrame(render); }}
// Netclass Net { constructor() { this.nodes = []; this.length = undefined; }
populate(length) { this.length = length;
for (var i = 0; i < length; i++) { var xPos = Math.floor(getRandom(0, canvas.width)); var yPos = Math.floor(getRandom(0, canvas.height)); this.nodes.push(new Node(xPos, yPos)); } }
update() { for (var i = 0; i < this.length; i++) { this.nodes[i].update(); } }
draw() { context.fillStyle = "#000000"; context.fillRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < this.length; i++) { this.nodes[i].draw(); } }
connect(distanceMax) { for (var i = 0; i < this.length - 1; i++) { this.nodes[i].connections = [];
for (var j = 0; j < this.length - 1; j++) { var a = this.nodes[j].x - this.nodes[i].x; var b = this.nodes[j].y - this.nodes[i].y; var c = Math.sqrt(a * a + b * b);
if (c < distanceMax) { this.nodes[i].connections.push(j); } }
for (var k = 0; k < this.nodes[i].connections.length; k++) { context.beginPath(); context.moveTo(this.nodes[i].x, this.nodes[i].y); context.lineTo( this.nodes[this.nodes[i].connections[k]].x, this.nodes[this.nodes[i].connections[k]].y ); context.strokeStyle = "rgba(255,255,255,.15)"; context.stroke(); } } }}
// Nodeclass Node { constructor(_x, _y) { this.x = _x; this.y = _y; this.radius = 2; this.depth = Math.floor(getRandom(1, 10)) / 10; }
update() { var velocity = (1 - this.depth) / 10; this.x = this.x + velocity;
if (this.x > canvas.width || this.x < 0) { this.x = 0; } }
draw() { var alpha = 1 - this.depth; context.beginPath(); context.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false); context.fillStyle = "rgba(255,255,255," + alpha + ")"; context.fill(); }}
// Helpersfunction getRandom(min, max) { return Math.random() * (max - min) + min;}
// Statsvar stats = new Stats();stats.showPanel(0);document.body.appendChild(stats.dom);
function animate() { stats.begin(); stats.end();
requestAnimationFrame(animate);}
requestAnimationFrame(animate);
body {  margin: 0;}
<html>    <head></head>    <body>        <canvas id="inner_heading-canvas" width="600" height="600"></canvas>    </body></html>

How do I create a simple slider with fade effect?

Add to your css:

.panel_switch { opacity: 0; transition: opacity 0.5s; }
.panel_switch_active { opacity: 1; }

Add the panel_switch_active class to the first slide

Add following javascript (and include jQuery):

$(function(){
$(".prev").click(function(){
$(".panel_switch_active").removeClass("panel_switch_active").prev().addClass("panel_switch_active");
});
$(".next").click(function(){
$(".panel_switch_active").removeClass("panel_switch_active").next().addClass("panel_switch_active");
});
});

This is pretty basic though. You might want to read up on javascript and jQuery or look for a suitable plugin.

Edit: I've created a jsfiddle with a fully working version: https://jsfiddle.net/1pp92v1u/

How can I make page slide onto the screen when button is clicked?

A very easy way to do this is with "animate.css".

All you do is dynamically apply the classes "animate slideInUp" (I think that's it anyway) to whatever element you want to slide in, and it just does.

You can do it with plain ol' JS, JQuery makes it braindead easy, bind it as a property in Angular/React (e.g. [ngClass]="theClasses"), however you want.

In your case in fact, you wouldn't even have to dynamically do anything. Just hardcode the classes to the topmost div (or whatever) of the HTML page that loads in. Every time that page loads in, it'll slide up.

Check out animate.css, it's a great and powerful tool and delivers exactly what it says it does, "just add water animations". For basic DOM element animation I've never had to look anywhere else.

You can see it at work on my little personal website:

http://www.tcoz.com

Every time you click a menu button, the page slides in.



Related Topics



Leave a reply



Submit