【发布时间】:2022-01-20 09:28:51
【问题描述】:
我有一个 11500x11500 的 div,它包含 400 张图像,显然溢出了视口。
我想以编程方式平移 整个 div。
我想生成一个动画,当动画结束时,整个 div 必须已经在视口中从上到下、从左到右平移。
现在,我正在将我的 11500x1500 div “拆分”为 tiles。每个图块的最大宽度和高度就是视口的宽度和高度。
我存储每个图块的坐标,然后随机选择一个,从左到右平移,然后移动到下一个。
我想知道:
- 我的方法是否正确,或者我的计算/方法中是否遗漏了一些东西,并且可以改进。考虑到尺寸,我很难判断我是否真的在平移整个 div
- 能否让平移效果感觉更“有机”/“自然”。为了确保整个 div 最终被平移,我选择每个图块并从左到右平移它,然后移动到下一个等等。这感觉有点僵硬和过于形式化。有没有办法以一个角度或一个更随机的运动进行平移,但要确保整个 div 最终会被平移?
提前感谢您的帮助。
这是jsfiddle,这是代码(为了示例/测试,每个“图像”实际上是一个包含其索引为文本的 div):
function forMs(time) {
return new Promise((resolve) => {
setTimeout(() => {
resolve()
}, time)
})
}
let container = document.getElementById('container')
let {
width,
height
} = container.getBoundingClientRect()
let minLeft = window.innerWidth - width
let minTop = window.innerHeight - height
let i = 0
while (i < 400) {
// adding "image" to the container
let image = document.createElement('div')
// add some text to the "image"
// to know what we're looking at while panning
image.innerHTML = ''
let j = 0
while (j < 100) {
image.innerHTML += ` ${i + 1}`
j++
}
container.appendChild(image)
i++
}
let coords = []
let x = 0
while (x < width) {
let y = 0
while (y < height) {
coords.push({
x,
y
})
y += window.innerHeight
}
x += window.innerWidth
}
async function pan() {
if (!coords.length) {
return;
}
let randomIdx = Math.floor(Math.random() * coords.length)
let [randomCoord] = coords.splice(randomIdx, 1);
console.log(coords.length)
container.classList.add('fast')
// update style in new thread so new transition-duration is applied
await forMs(10)
// move to new yet-unpanned area
container.style.top = Math.max(-randomCoord.y, minTop) + 'px'
container.style.left = Math.max(-randomCoord.x, minLeft) + 'px'
// wait (approx.) for transition to end
await forMs(2500)
container.classList.remove('fast')
// update style in new thread so new transition-duration is applied
await forMs(10)
//pan that area
let newLeft = -(randomCoord.x + window.innerWidth)
if (newLeft < minLeft) {
newLeft = minLeft
}
container.style.left = newLeft + 'px'
// wait (approx.) for transition to end
await forMs(4500)
// move on to next random area
await pan()
}
pan()
html,
body {
position: relative;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
overflow: auto;
}
* {
margin: 0;
padding: 0;
}
#container {
position: absolute;
top: 0;
left: 0;
text-align: left;
width: 11500px;
height: 11500px;
transition: all 4s ease-in-out;
transition-property: top left;
font-size: 0;
}
#container.fast {
transition-duration: 2s;
}
#container div {
display: inline-block;
height: 575px;
width: 575px;
border: 1px solid black;
box-sizing: border-box;
font-size: 45px;
overflow: hidden;
word-break: break-all;
}
<div id="container"></div>
【问题讨论】:
标签: javascript html css css-transitions panning