我一直在寻找一个满意的答案,这一段时间使用谷歌/Stackoverflow和ChatGPT,但我真的不能弄清楚。
我试图创建一个包含3 x 3个小盒子(正方形)的盒子(主容器)。我们的想法是让主容器的z索引比square高,让square透明,这样当我对某个东西进行动画时,动画元素(比如z索引为1)在穿过正方形之间的空间时会被隐藏(例如,当你看到一个物体时)。主容器的可见部分),但是当穿过正方形时可见。
下面的代码可以工作,但只使用黑色作为主容器的背景色。我希望能够获得相同的结果与任何颜色。
// Create a colored square element
var square = document.createElement('div');
square.style.width = '2vw';
square.style.height = '2vw';
square.style.backgroundColor = 'red';
square.style.position = 'absolute';
// Set the initial position of the square to center left
square.style.left = '0';
square.style.top = 'calc(50vh - 1vw)';
// Add the square element to the page
document.body.appendChild(square);
// Animate the square
function animateSquare() {
var currentPosX = parseFloat(square.style.left);
// Update the square's position
var newPosX = currentPosX + 5; // Move the square to the right by 5 pixels
square.style.left = newPosX + 'px';
// Check if the square has reached the center right
if (newPosX + square.offsetWidth >= window.innerWidth / 2) {
// If the square has reached the center right, stop animating
return;
}
// Continue animating
requestAnimationFrame(animateSquare);
}
// Start the animation
animateSquare();
.main-container {
position: relative;
margin: auto;
display: flex;
flex-wrap: wrap;
width: 30vw;
height: 30vw;
align-items: center;
justify-content: space-evenly;
padding: 1%;
border: solid 1px gray;
border-radius: 10%;
background-color: black;
mix-blend-mode: hard-light;
z-index: 3;
}
.square {
width: 24%;
height: 24%;
margin: 1%;
border-radius: 20%;
background-color: rgb(204, 118, 118);
z-index: -1;
}
<div class="main-container">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
2条答案
按热度按时间oxf4rvwz1#
使用
<clipPath id="clip" clipPathUnits="objectBoundingBox">
创建一个SVG图像(更容易使用SVG编辑器),并将其用作元素的CSSclip-path
这里有一个9个正方形的例子(你可以像你的例子一样创建圆形边框的正方形。这是一个概念的证明)
如果你想让你的球即使在外面也能看到,那么任务就更简单了。创建一个带有所需穿孔(圆形正方形)的黑色SVG形状,在其容器内使用该形状的z索引,确保球的z索引低于穿孔形状。
guykilcj2#
我认为你需要一个元素的遮罩。请参阅this Clipping and Masking in CSS文章,但您必须自己创建矢量。
创建一个与您提供的图片完全相同的矢量,但只填充您希望动画可见的位置。然后简单地遮罩正在为矢量设置动画的元素。
下面是文章中的一个例子