const canvas = document.querySelector('canvas'); const image = document.querySelector('.logo'); const ctx = canvas.getContext('2d'); const deviceType = () => { const ua = navigator.userAgent; if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(ua)) { return "tablet"; } else if (/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(ua)) { return "mobile"; } return "desktop"; }; if(deviceType() === "mobile" || deviceType() === "tablet"){ canvas.style.display = 'none'; image.style.display = 'block'; }else{ image.style.display = 'none'; } let width = canvas.width = window.innerWidth; let height = canvas.height = window.innerHeight; let fps_counter = 0; let particleArray = []; initParticleSize = 1.5; // handle mouse const mouse = { x: null, y: null, radius: 200, } window.addEventListener('mousemove', function(event) { mouse.x = event.x; mouse.y = event.y; }); window.addEventListener('resize', function(){ width = canvas.width = window.innerWidth; height = canvas.height = window.innerHeight; init(); }); ctx.fillStyle = 'black'; ctx.font = '30px Verdana'; class Particle{ constructor(x, y, color){ this.x = x; this.y = y; this.size = initParticleSize; this.baseX = this.x; this.baseY = this.y; this.density = (Math.random() * 30) + 1; // this.density = 30; } draw(){ ctx.fillStyle = this.color; ctx.beginPath(); ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2); ctx.closePath(); ctx.fill(); } update(){ let dx = mouse.x - this.x; let dy = mouse.y - this.y; let distance = Math.sqrt(dx * dx + dy * dy); let forceDirectionX = (dx / distance); let forceDirectionY = (dy / distance); let maxDistance = mouse.radius; let force = (maxDistance - distance) / maxDistance; let directionX = forceDirectionX * force * this.density; let directionY = forceDirectionY * force * this.density; if (distance < mouse.radius){ this.x -= directionX; this.y -= directionY; } else { if (this.x !== this.baseX){ let dx = this.x - this.baseX; this.x -= dx/10; } if (this.y !== this.baseY){ let dy = this.y - this.baseY; this.y -= dy/10; } } } } function init(){ particleArray = [] fetch("x_y_100w_v2.json") .then(Response => Response.json()) .then(data => { let adjustX = width / 2 - 300; let adjustY = height / 2 - 315; data.arr.forEach((element) => { particleArray.push(new Particle(element.x + adjustX, element.y + adjustY)); }); }).catch(err => console.log(err)) } function animate(){ ctx.clearRect(0, 0, width, height); particleArray.forEach(particle => { particle.draw(); particle.update(); }) requestAnimationFrame(animate); } if (deviceType() === "desktop"){ init(); animate(); }