


How to use CSS and D3 to implement interactive animation of small fish swimming (with code)
The content of this article is about how to use CSS and D3 to realize interactive animation of small fish swimming (with code). It has certain reference value. Friends in need can refer to it. I hope It will help you.
Effect preview
Source code download
https://github.com/comehope/front- end-daily-challenges
Code Interpretation
Define dom, the sub-elements contained in the container represent the body, eyes, dorsal fin and tail of the fish respectively:
<div> <span></span> <span></span> <span></span> <span></span> </div>
Set page style For full screen and no scroll bars:
body { margin: 0; width: 100vw; height: 100vh; background-color: #222; overflow: hidden; }
Define the container size of the fish, --r
is a basic size unit, and all subsequent sizes are calculated based on it:
.fish { position: absolute; --r: 15vw; width: calc(var(--r) + var(--r) / 3); height: calc(var(--r) * 2); left: 50%; top: 100px; }
Draw the body of the fish, and declare the color of the fish to the parent class, because this color will be used below:
.fish { color: hsl(0, 50%, 50%); } .fish .body { position: absolute; border: var(--r) solid transparent; border-right-color: currentColor; border-left-style: none; }
Draw the eyes of the fish:
.fish .eye { position: absolute; --r1: calc(var(--r) / 4); width: var(--r1); height: var(--r1); background-color: #111; border-radius: 50%; top: 35%; left: 30%; }
Draw The dorsal fin of the fish:
.fish .fin { position: absolute; --r2: calc(var(--r) / 2); border-bottom: var(--r2) solid; border-left: var(--r2) solid transparent; filter: brightness(2.5); left: calc(var(--r) - var(--r2)); }
Draw the tail of the fish:
.fish .tail { position: absolute; --r3: calc(var(--r) / 3); border: var(--r3) solid transparent; border-right-color: currentColor; border-left-style: none; right: 0; top: calc(var(--r) - var(--r3)); }
Add the animation effect for the fish to swim, not to execute it in a loop, but only once:
.fish { right: calc(var(--r) * -1); animation: run 3s linear forwards; } @keyframes run { to { right: 100%; } }
Then add the animation effect of the swaying of the fish when swimming:
.fish { animation: run 3s linear forwards, shake 0.3s linear infinite; } @keyframes shake { 50% { transform: rotateY(-30deg); } 100% { transform: rotateY(30deg); } }
Next, set some variables to create different-looking fish:
Variables for the size of the fish--size
, the larger the value, the larger the size:
.fish { --size: 5; --r: calc(var(--size) * 1vw); }
The color variable of the fish--color
, indicating the angle of the hue circle:
.fish { --color: 0; color: hsl(var(--color), 50%, 50%); }
The fish swims from the right to the left The duration on the side, the shorter the duration, the faster the fish swims:
.fish { --duration: 3; animation: run calc(var(--duration) * 1s) linear forwards, shake 0.3s linear infinite; }
The height at which the fish appears, the larger the data, the closer it is to the lower part of the page:
.fish { --top: 100; top: calc(var(--top) * 1px); }
Next, use d3 to batch process dom elements and css variables .
Introduce the d3 library:
<script></script>
Delete the .fish
element in the html and the variable declaration code in the css file. Create a function that generates a fish. The values of css variables are randomly generated. The value range of --size
is 5 ~ 8, the value range of --color
is -60 ~ 15, - The value range of -duration
is 3 ~ 6, the value range of --top
is 100 ~ 300:
function buildFish() { let fish = d3.select('body') .append('p') .attr('class', 'fish') .style('--size', d3.randomUniform(5, 8)()) .style('--color', d3.randomUniform(-60, 15)()) .style('--duration', d3.randomUniform(3, 6)()) .style('--top', d3.randomUniform(100, 300)()); fish.append('span').attr('class', 'body'); fish.append('span').attr('class', 'eye'); fish.append('span').attr('class', 'fin'); fish.append('span').attr('class', 'tail'); }
binds the mouse click event. When the mouse is pressed A fish is generated when the It goes blank after loading:
function buildFish(e) { //略.... .style('--top', e.clientY); } window.addEventListener('click', buildFish);
Done!
Related recommendations:
How to use pure CSS to achieve the text effect of tearing tinfoil (with code)How to use pure CSS to achieve it Animation effect of an hourglass
The above is the detailed content of How to use CSS and D3 to implement interactive animation of small fish swimming (with code). For more information, please follow other related articles on the PHP Chinese website!

Choosing Flexbox or Grid depends on the layout requirements: 1) Flexbox is suitable for one-dimensional layouts, such as navigation bar; 2) Grid is suitable for two-dimensional layouts, such as magazine layouts. The two can be used in the project to improve the layout effect.

The best way to include CSS files is to use tags to introduce external CSS files in the HTML part. 1. Use tags to introduce external CSS files, such as. 2. For small adjustments, inline CSS can be used, but should be used with caution. 3. Large projects can use CSS preprocessors such as Sass or Less to import other CSS files through @import. 4. For performance, CSS files should be merged and CDN should be used, and compressed using tools such as CSSNano.

Yes,youshouldlearnbothFlexboxandGrid.1)Flexboxisidealforone-dimensional,flexiblelayoutslikenavigationmenus.2)Gridexcelsintwo-dimensional,complexdesignssuchasmagazinelayouts.3)Combiningbothenhanceslayoutflexibilityandresponsiveness,allowingforstructur

What does it look like to refactor your own code? John Rhea picks apart an old CSS animation he wrote and walks through the thought process of optimizing it.

CSSanimationsarenotinherentlyhardbutrequirepracticeandunderstandingofCSSpropertiesandtimingfunctions.1)Startwithsimpleanimationslikescalingabuttononhoverusingkeyframes.2)Useeasingfunctionslikecubic-bezierfornaturaleffects,suchasabounceanimation.3)For

@keyframesispopularduetoitsversatilityandpowerincreatingsmoothCSSanimations.Keytricksinclude:1)Definingsmoothtransitionsbetweenstates,2)Animatingmultiplepropertiessimultaneously,3)Usingvendorprefixesforbrowsercompatibility,4)CombiningwithJavaScriptfo

CSSCountersareusedtomanageautomaticnumberinginwebdesigns.1)Theycanbeusedfortablesofcontents,listitems,andcustomnumbering.2)Advancedusesincludenestednumberingsystems.3)Challengesincludebrowsercompatibilityandperformanceissues.4)Creativeusesinvolvecust

Using scroll shadows, especially for mobile devices, is a subtle bit of UX that Chris has covered before. Geoff covered a newer approach that uses the animation-timeline property. Here’s yet another way.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
