Last active
May 5, 2020 19:57
-
-
Save rafanake/c4fbd6fd20974e74daa55124f09ed863 to your computer and use it in GitHub Desktop.
JavaScript - Torn Paper effect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
tornPaper = options => { | |
let defaults = { | |
selector: null, | |
offset: 50, | |
stepX: 5, | |
stepY: 5, | |
extra: null | |
}; | |
const params = Object.assign(defaults, options); | |
let elements = document.querySelectorAll(params.selector); | |
if (elements.length <= 0) { | |
console.error(`selector: ${params.selector} not found`); | |
return false; | |
} | |
elements.forEach(function (currentValue, currentIndex, listObj) { | |
// console.log(this); # params.extra | |
let width = currentValue.offsetWidth; | |
let height = currentValue.offsetHeight; | |
let offSet = params.offset | |
let lastX = 0; | |
let lastY = height - offSet; | |
let pointsArray = []; | |
pointsArray.push(`0px 0px`); | |
pointsArray.push(`0px ${lastY}px`); | |
while (lastX < width) { | |
let randX = Math.floor(Math.random() * params.stepX) + 3; | |
let randY = Math.floor(Math.random() * params.stepY) * (Math.random() < 0.5 ? -1 : 1); | |
// fix width | |
lastX += randX; | |
if (lastX > width) { | |
lastX = width; | |
} | |
// fix height | |
if ((randY + lastY >= height) || (randY + lastY < (height - offSet))) { | |
randY = randY * -1; | |
} | |
lastY += randY; | |
pointsArray.push(`${lastX}px ${lastY}px`); | |
} | |
pointsArray.push(`${width}px 0px`); | |
currentValue.style.clipPath = `polygon(${pointsArray.join(', ')})`; | |
}, params.extra); | |
}; | |
// how to use it | |
tornPaper({ | |
selector: '.box' | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment