I am posting html and javascript code where i am trying to set an origin and move all the divs in all directions. Say, i have created 8 divs for 8 directions and then I am trying to move them respectively to their new positions with @keyframes.
I have tried by getting the center position of the origin div and then I have created an array of numbers which will determine the new x and y pos. However, all the divs (i guess) are together stucked and then moving at a same pace and direction. I tried to figure out the problem but I wasnt able to achieve the target.
Here is my code:
class Explosion{
constructor(){
this.widget = null
}
setWidget = (widget) => {
this.widget = widget
}
createExplosion = () => {
const centerX = this.widget.getBoundingClientRect().x + parseInt(this.widget.getBoundingClientRect().width / 2)
const centerY = this.widget.getBoundingClientRect().y + parseInt(this.widget.getBoundingClientRect().height / 2)
const finalPos = [[-10 , -10] , [0 , -10] , [10 , -10] , [10 , 0] , [10 , 10] , [0 , 10] , [-10 , 10] , [-10 , 0]]
this.rocks = []
for(let i = 0; i < finalPos.length; i++){
var rock = document.createElement("div")
rock.style.width = "10px"
rock.style.height = "10px"
rock.style.borderRadius = "50%"
rock.style.position = "absolute"
rock.style.backgroundColor = "#2E3440"
rock.style.left = centerX + 'px'
rock.style.top = centerY + "px"
var style = document.createElement("style")
style.innerHTML = `
@keyframes movingAnimation{
0%{
left: ${centerX}px;
top: ${centerY}px;
}
100%{
left: ${Math.abs(centerX + finalPos[i][0])}px;
top: ${Math.abs(centerY + finalPos[i][1])}px;
}
}
`
rock.appendChild(style)
setTimeout((rock) => {
rock.style.display = "none"
} , 10000 , rock)
rock.style.animation = "movingAnimation 10000ms"
this.rocks.push(rock)
document.body.appendChild(rock)
}
this.widget.style.display = "none"
}
}
const explosion = new Explosion()
const origin = document.querySelector(".origin")
explosion.setWidget(origin)
explosion.createExplosion()
Html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test</title>
</head>
<body>
<div class="origin" style="width: 100px; height: 100px; background-color: #2E3440"></div>
<script src="test.js"></script>
</body>
</html>
Aucun commentaire:
Enregistrer un commentaire