Reputation: 2097
I animated an svg curve using Javascript, and it works great! However, when you resize the window, it doesn't resize to fit it. Is there any way to do this? I am open to any solutions, whether it is CSS, JS, or HTML (or another language, for that matter). Here is the code I am using:
const vw = document.body.clientWidth
const vh = document.body.clientHeight
let wave = -2890
function add(){
if(wave === -2){
wave = -2890
} else {
wave = wave + 2
}
document.getElementById('main').innerHTML = `<div class="wave" id="main" transform="rotate(1)"><svg width="${vw}px" height="25px" viewBox="0 0 1440 25" preserveAspectRatio="none"><g width="${vw}px" data-svg-origin="0 0" transform="matrix(1,0,0,1, ${wave + Math.floor(Math.random() * 10) -10},0)" style="transform-origin: 0px 0px;"><path width="${vw}px" fill="currentColor" d="M 0 12.5 q 360 -25 720 0 t 720 0 t 720 0 t 720 0 t 720 0 t 720 0 V 0 H 0 V 12.5"></path></g></svg></div>`
requestAnimationFrame(add);
}
requestAnimationFrame(add);
<div class="wave" id="main"></div>
For example, if you run the code snippet not in full screen, and then enter full screen, you can see that it stays with its initial width.
Help is appreciated. Thanks!
Upvotes: 2
Views: 53
Reputation: 273458
move the variables inside the function:
let wave = -2890
function add() {
let vw = document.body.clientWidth
let vh = document.body.clientHeight
if (wave === -2) {
wave = -2890
} else {
wave = wave + 2
}
document.getElementById('main').innerHTML = `<div class="wave" id="main" transform="rotate(1)"><svg width="${vw}px" height="25px" viewBox="0 0 1440 25" preserveAspectRatio="none"><g width="${vw}px" data-svg-origin="0 0" transform="matrix(1,0,0,1, ${wave + Math.floor(Math.random() * 10) -10},0)" style="transform-origin: 0px 0px;"><path width="${vw}px" fill="currentColor" d="M 0 12.5 q 360 -25 720 0 t 720 0 t 720 0 t 720 0 t 720 0 t 720 0 V 0 H 0 V 12.5"></path></g></svg></div>`
requestAnimationFrame(add);
}
requestAnimationFrame(add);
<div class="wave" id="main"></div>
Upvotes: 2