You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

46 lines
1.6 KiB
JavaScript

3 years ago
// A lightweight sticker spawner to stick elements on your html page
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);
}
}
}