This article brings you the content is about how to use CSS and D3 to achieve the animation effect of black and white overlap, the article introduced the JS in this understanding, there is a certain reference value, the need for a friend can refer to, I hope you have some help.
Effect Preview
Code interpretation
Defines the DOM, which contains 3 child elements, each of which represents a circle:
<div class= "Circles" > <span></span> <span></span> <span></ Span></div>
Center display:
body { margin:0; HEIGHT:100VH; Display:flex; Align-items:center; Justify-content:center; Background-color:black;}
Define Container Dimensions:
. circles { width:60vmin; Height:60vmin;}
Draw 1 circles in the container:
. circles { position:relative;}. Circles span { position:absolute; Box-sizing:border-box; width:50%; height:50%; Background-color:white; border-radius:50%; left:25%;}
Define variables, draw multiple circles, and each circle rotates around the bottom midpoint of the 1th circle, enclosing a larger circle:
. circles { --particles:3;}. Circles span { Transform-origin:bottom center; --deg:calc (360deg/var (--particles) * (Var (--n)-1)); Transform:rotate (Var (--deg));}. Circles Span:nth-child (1) { --n:1;}. Circles Span:nth-child (2) { --n:2;}. Circles Span:nth-child (3) { --n:3;}
Add animation to child elements:
. Circles span { animation:rotating 5s ease-in-out Infinite;} @keyframes Rotating { 0% { transform:rotate (0); } 50% { transform:rotate (Var (--deg)) Translatey (0); } 100% { transform:rotate (Var (--deg)) Translatey (100%) scale (2);} }
Set the sub-element blending mode so that the overlapping portions of the child elements appear black:
. Circles span { mix-blend-mode:difference;}
Add animation to the container, offset the magnification of the child elements, and smooth the animation:
. Circles { animation:zoom 5s linear Infinite;} @keyframes Zoom {To { Transform:scale (0.5) Translatey ( -50%);} }
Next, the DOM elements and CSS variables are processed in bulk using D3.
Introducing the D3 Library:
<script src= "Https://d3js.org/d3.v5.min.js" ></script>
Use D3 to assign values to variables that represent the number of circles:
Const Count_of_particles = 30;d3.select ('. Circles ') . Style ('--particles ', count_of_particles)
To generate DOM elements with D3:
D3.select ('. Circles ') . Style ('--particles ', count_of_particles). selectall (' span ') . Data (D3.range ( count_of_particles) . Enter () . Append (' span ');
Assign a value to a variable that represents a sub-element subscript using D3:
D3.select ('. Circles ') . Style ('--particles ', count_of_particles). selectall (' span ') . Data (D3.range ( count_of_particles) . Enter (). append (' span ') . Style ('--n ', (d) = + D + 1);
Delete the associated DOM elements in the HTML file and the associated CSS variables in the CSS file.
Finally, adjust the number of circles to 30:
Const Count_of_particles = 30;
Done!