UNPKG

@igor-j86/snowflakes

Version:
72 lines (71 loc) 3.28 kB
import * as React from "react"; export var Snowflakes = function (_a) { var _b = _a.id, id = _b === void 0 ? "snowflakes" : _b, _c = _a.snowflakes, snowflakes = _c === void 0 ? 100 : _c, _d = _a.maxSize, maxSize = _d === void 0 ? 3 : _d, _e = _a.maxSpeed, maxSpeed = _e === void 0 ? 0.5 : _e, _f = _a.color, color = _f === void 0 ? '#dddddd' : _f; var canv = React.useRef(null); React.useEffect(function () { if (canv.current) { var NUMBER_OF_FLAKES = snowflakes; var MAX_FLAKES_SIZE_1 = maxSize; var MAX_FLAKES_BLUR_1 = 2; var MAX_FLAKES_SPEED_1 = maxSpeed; var FLAKES_COLOR_1 = color; var flakes_1 = []; canv.current.style.position = 'fixed'; canv.current.style.top = '0'; canv.current.style.left = '0'; canv.current.style.pointerEvents = 'none'; canv.current.width = window.innerWidth; canv.current.height = window.innerHeight; var ctx_1 = canv.current.getContext('2d'); var createFlake_1 = function () { return canv.current && ({ x: Math.random() * canv.current.width, y: Math.random() * canv.current.height - canv.current.height, radius: Math.random() * MAX_FLAKES_SIZE_1 + 3, transparency: Math.random(), blur: Math.random() * MAX_FLAKES_BLUR_1, color: FLAKES_COLOR_1, speed: Math.random() * MAX_FLAKES_SPEED_1 + 1, sway: Math.random() - 0.5 }); }; var drawFlakes_1 = function (flake) { if (ctx_1) { ctx_1.beginPath(); ctx_1.arc(flake.x, flake.y, flake.radius, 0, Math.PI * 2); ctx_1.fillStyle = flake.color; ctx_1.filter = "blur(".concat(flake.blur, "px)"); ctx_1.globalAlpha = flake.transparency; ctx_1.fill(); ctx_1.closePath(); } }; var updateFlakes_1 = function (flake) { flake.y += flake.speed; flake.x += flake.sway; if (canv.current && flake.y > canv.current.height) { Object.assign(flake, createFlake_1()); } }; var animate_1 = function () { if (ctx_1 && canv.current) { ctx_1.clearRect(0, 0, canv.current.width, canv.current.height); flakes_1.forEach(function (flake) { updateFlakes_1(flake); drawFlakes_1(flake); }); requestAnimationFrame(animate_1); } }; for (var i = 0; i < NUMBER_OF_FLAKES; i++) { flakes_1.push(createFlake_1()); } window.addEventListener('resize', function () { if (canv.current) { canv.current.width = window.innerWidth; canv.current.height = window.innerHeight; } }); animate_1(); } }, [canv]); return React.createElement("canvas", { ref: canv, id: id }); };