From caa9023bbfc7abc13aee9ab8d4a53009cfa0b03c Mon Sep 17 00:00:00 2001 From: Francesco Date: Wed, 26 Jan 2022 18:41:05 +0100 Subject: [PATCH] init --- spawnSticker.js | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 spawnSticker.js diff --git a/spawnSticker.js b/spawnSticker.js new file mode 100644 index 0000000..411ef24 --- /dev/null +++ b/spawnSticker.js @@ -0,0 +1,46 @@ + +const stickerSpawners = document.querySelectorAll("[data-sticker]"); +var throttleSpawn = throttle(spawnSticker, 400); + +Array.from(stickerSpawners).forEach((spawner) => { + spawner.addEventListener("mousemove", (e) => throttleSpawn(e)); +}); + +function spawnSticker(e) { + var rect = e.target.getBoundingClientRect(); + let position = { x: e.clientX - rect.left, y: e.clientY - rect.top }; + let content = e.target.dataset.sticker; + e.originalTarget.appendChild(createSticker(content, position)); +} + + +function createSticker(content, position) { + sticker = document.createElement("span"); + sticker.classList.add("sticker"); + sticker.innerHTML = content; + sticker.style.left = position.x + "px"; + sticker.style.top = position.y + "px"; + + sticker.style.transform = ` + translate(-50%, -50%) + rotate(${Math.random() * 40 - 20}deg) + `; + + return sticker; +} + + +// from https://stackoverflow.com/questions/27078285/simple-throttle-in-javascript + +function throttle (callback, limit) { + var waiting = false; // Initially, we're not waiting + return function () { // We return a throttled function + if (!waiting) { // If we're not waiting + callback.apply(this, arguments); // Execute users function + waiting = true; // Prevent future invocations + setTimeout(function () { // After a period of time + waiting = false; // And allow future invocations + }, limit); + } + } +} \ No newline at end of file