Enchanting Hexagons: A Dazzling Display of Mesmerizing Animations with HTML, CSS & JS

Enchanting Hexagons: A Dazzling Display of Mesmerizing Animations with HTML, CSS & JS

??? Get ready to dive into a world of enchantment as we embark on a mesmerizing journey of creating Enchanting Hexagons! ??? Brace yourself for a dazzling display of captivating animations that will leave you spellbound. ??

? In this magical tutorial, we'll weave the spell using the potent combination of HTML, CSS, and JavaScript. ??? Get ready to witness hexagons come alive with charm and charisma! ???? Let's infuse our code with magic and create a truly enchanting web experience! ???

HTML Code :

??? Hexagonal Harmony: Unlocking the Enchantment of Hexagons ???

Let's embark on a journey where the bedrock of our creation lies in the robust structure of HTML. Picture this foundation as the canvas on which we'll paint our digital masterpiece. Now, enters CSS, the virtuoso responsible for adding a touch of glamour.

Yet, the true enchantment comes alive through the wizardry of JavaScript. Here, the code transcends mere instructions, transforming into a magical force that breathes life into our creation.

The output of the HTML Code :

???We are now poised to enhance the visual appeal of the webpage by incorporating some CSS magic that will truly make it sparkle! ??? To elevate the aesthetics and create a professional touch, we'll infuse the page with a touch of style. Let's embark on this journey to elevate our web presence to new heights! ????

CSS Code :

???? CSS Aesthetics: Elevating Web Design with Style & Charm! ???

Elevate your web presentation to new heights with a design that effortlessly commands attention on any device! Bid farewell to awkward gaps as your HTML and body elements seamlessly embrace 100% of the viewport height. Embrace a flawless aesthetic by setting margins to 0, ensuring your content captivates without distraction.

Ditch the scrolling dilemmas with a touch of overflow: hidden, ensuring your content stays polished and perfectly contained. Say hello to a sleek user experience where every element takes center stage, unencumbered by unwanted spacing.

And the grand finale? Picture a backdrop of sophistication in a deep, customizable black. Tailor the RGB values to your brand's essence, crafting a visually stunning canvas that not only complements but enhances your content.

The output of the CSS Code :

All right, buckle up! ?? Time to inject some JavaScript magic into the mix and bring our animation to life! ? Get ready for a visual feast as we unleash the power of code to make things move and groove on your screen. ?? Let the animation extravaganza begin! ????

JS Code :

???? Canvas Magic: Understanding the Core of HTML5 Graphics ???

The first line establishes a connection to an HTML <canvas> element using document.querySelector('canvas'). This line is essentially grabbing the canvas element from the HTML document and assigning it to the variable cnv.

The second line initiates a 2D rendering context with getContext('2d'). The ctx variable now holds the drawing functions and properties needed to manipulate the canvas. It's like having a powerful paintbrush ready to create graphics on our canvas.

The next three lines (let cw, ch, cx, cy) declare variables for the canvas width (cw), canvas height (ch), canvas center x-coordinate (cx), and canvas center y-coordinate (cy). These will prove crucial for positioning and sizing elements within the canvas.

?? Understanding the Canvas Coordinate System ???

The canvas, like any artist's canvas, has its coordinate system. The top-left corner is the origin (0,0), with positive x extending to the right and positive y extending downward. The cx and cy variables will help us find the center of the canvas.

??? Adapting to Change: Dynamic Canvas Resizing in Action ??????

The function resizeCanvas serves as the architect behind the canvas's ability to adjust to varying window sizes. Here's a breakdown of its actions:

  • cw and ch are updated to match the current width and height of the window.
  • cnv.width and cnv.height set the canvas dimensions to match the window size.
  • cx and cy are recalculated to represent the new center of the canvas.

The resizeCanvas() function is called immediately when the script runs, ensuring the canvas is appropriately sized right from the start.

The window.addEventListener('resize', resizeCanvas) line ensures that every time the user resizes the browser window, the resizeCanvas function is called again. This responsiveness guarantees that the canvas dynamically adjusts to the new window dimensions, providing a seamless and visually pleasing user experience.

??? Why Dynamic Canvas Resizing Matters ??

  • Cross-Device Compatibility: In an era of diverse devices and screen sizes, dynamic canvas resizing ensures your graphics adapt gracefully to different platforms, from desktops to mobile devices.
  • User Experience Enhancement: A canvas that scales with the window provides a consistent and engaging user experience, preventing awkward cutoffs or unnecessary scrollbars.
  • Responsive Visuals: For interactive web applications or games, adapting the canvas size allows for more responsive and immersive visuals, creating a fluid and enjoyable user interaction

????? Palette of Hexagons: Hexagon Animation Configurations ????

We'll start by dissecting a configuration object that serves as the mastermind behind the mesmerizing visual experience.

  • hue: The hue parameter controls the color tone of the hexagons. As it varies, it introduces a dynamic range of colors, providing a visually stimulating experience.
  • bgFillColor: The background fill color (bgFillColor) is set to a transparent dark shade (rgba(33, 33, 33, .01)). This choice subtly maintains the canvas's previous state, creating a visually smooth animation effect.
  • dirsCount: dirsCount determines the number of directions the hexagons can move. In this case, there are six directions, contributing to the hexagonal pattern.
  • stepToTurn: This parameter defines how much each hexagon turns in each step, influencing the overall rotation and movement pattern.
  • hexSize: The hexSize parameter dictates the initial size of each hexagon, serving as the building block for the overall composition.
  • hexCount: With hexCount set to 100, the canvas will host a bustling community of 100 hexagons, each contributing to the dynamic and intricate visual display.
  • hexVelocity: hexVelocity controls the speed at which the hexagons move across the canvas, adding an element of motion and life to the animation.
  • distance: distance sets the distance between the hexagons, influencing the overall density of the pattern.
  • gradientLen: The gradientLen parameter introduces a gradient effect, adding depth and dimensionality to the hexagons.
  • shadowBlur: Lastly, shadowBlur applies a subtle blur effect to the hexagon shadows, contributing to the visual aesthetics.

?? Unleashing Creativity ???

This configuration object encapsulates the essence of a visually striking hexagon animation. Tinkering with these parameters opens the door to a myriad of artistic possibilities, allowing developers and artists alike to shape and mold their visual masterpieces.

?????? Brushing the Canvas: The DrawHexagon Function Unveiled ?????

Here, we're dissecting a function that acts as the artisan's brush, painting the canvas with hexagonal strokes of creativity. Behold the drawHexagon function, a key player in crafting the mesmerizing hexagon animation.

  • ctx.globalCompositeOperation: The globalCompositeOperation property sets how new shapes are drawn onto existing shapes. This allows for blending and layering effects, offering a versatile tool for artistic expression.
  • ctx.shadowBlur: The shadowBlur property controls the blurring effect applied to the hexagon's shadow. If not provided (blur || 1), a default blur of 1 is applied. This shadow adds depth and dimension to the hexagon, enhancing its visual impact.
  • ctx.fillStyle: The fillStyle property sets the fill color of the hexagon. It's the palette from which the hexagon draws its vibrant hues.
  • Hexagon Drawing Logic: ctx.beginPath() initiates the path for the hexagon. A loop runs six times, drawing the six vertices of the hexagon. The angle calculation ensures each vertex is evenly spaced around the center.hexX and hexY compute the coordinates of each vertex based on the center (x, y) and the size of the hexagon. The loop moves to the first vertex or draws a line to subsequent vertices, forming the hexagon.ctx.closePath() ensures the shape is closed.
  • ctx.fill(): The fill() method fills the hexagon with the specified color, bringing the shape to life on the canvas.

?? The Canvas Comes Alive ??

As we witness the drawHexagon function in action, we gain insight into the meticulous craftsmanship behind hexagon animations. This function serves as the brushstroke that paints the canvas with vibrant colors, shadows, and intricate patterns.

????Choreography of Hexagons: The Dance of the Hexagon Class ????

Here, we're unraveling the dance of hexagons orchestrated by the Hexagon class, a pivotal piece in the canvas performance.

  • constructor: Initializes a hexagon at the canvas center (cx, cy). Assign a random initial direction. Sets the step count to 0.
  • redrawHexagon: Calculates color and style attributes based on the hexagon's position.Invokes the drawHexagon function, painting the hexagon on the canvas.
  • moveHexagon: Advances the hexagon's position based on its current direction and velocity.
  • changeDir: Periodically changes the hexagon's direction, introducing a dynamic and unpredictable movement pattern.
  • killHexagon: Determines a probability of hexagon removal based on its step count and distance traveled. If the probability exceeds a threshold, the hexagon gracefully exits the canvas performance.

? The Hexagon Ballet ??

The Hexagon class exemplifies the dynamic and ever-changing nature of web artistry. Each instance is a dancer, gracefully moving across the canvas, changing directions, and, in a poetic finale, exiting the stage.

?????Orchestrating the Ensemble: Generating Directions & Hexagons????

Now we're unraveling the behind-the-scenes script that populates the stage with directions and brings forth the ensemble of hexagons.

??? Generating Directions:

  • dirsList Initialization: A loop creates a list of direction vectors (dirsList) evenly distributed around a circle. Each vector represents a direction in which a hexagon can move.

?? Bringing Forth the Hexagon Ensemble:

  • addHexagon Function: Checks if the current number of hexagons on stage is less than the specified count (hexCfg.hexCount) and if a random condition is met. If conditions are met, a new Hexagon instance is created and added to the hexagonsList array. The hue value in the configuration (hexCfg.hue) is incremented to introduce color variation among hexagons.

?? The Choreography Continues ??

These lines of code contribute to the dynamic and evolving nature of the canvas performance. This dirsList ensures hexagons have predefined directions to follow, creating a cohesive movement pattern. The addHexagon function, with its randomness, adds an element of spontaneity to the ensemble, ensuring that each hexagon enters the stage at its own pace.

???? Enlivening the Canvas: The Rhythmic Pulse of refreshHexagons ???

Now we're gonna implement a key function that orchestrates the lively rhythm of the hexagon ensemble on the canvas. Let's explore the dance moves encapsulated in the refreshHexagons function.

  • hexagonsList.forEach: Iterates through each hexagon in the hexagonsList.
  • i.redrawHexagon(): Initiates the method to redraw the hexagon on the canvas. Calculates and applies the color, blur, and position attributes.
  • i.moveHexagon(): Advances the hexagon's position based on its current direction and velocity. The hexagon continues its graceful movement across the canvas.
  • i.changeDir(): Periodically changes the hexagon's direction, introducing unpredictability and dynamism. The hexagon adapts its course in response to the changing winds.
  • i.killHexagon(id): Evaluate the hexagon's lifespan based on its step count and distance traveled. If the hexagon has reached the end of its performance, it exits the stage gracefully.

?? The Dance of Hexagons Continues ??

The refreshHexagons function serves as the heartbeat of the canvas, ensuring each hexagon plays its part in the synchronized dance. Redrawing, moving, changing direction, and assessing vitality, these actions harmonize to create a dynamic and visually captivating spectacle.

???? The Eternal Ballet: Initiating the Canvas Loop ????

We conclude our exploration by uncovering the mesmerizing canvas loop that orchestrates the perpetual dance of hexagons. Behold the enchanting loop function.

  • drawHexagon: Initiates the drawing of a background hexagon, essentially clearing the canvas for the next frame. Utilizes hexCfg.bgFillColor to set the background color. Spans the entire canvas (cw, ch).
  • addHexagon: Invokes the function responsible for adding new hexagons to the canvas. Ensures the ensemble continues to grow, introducing new performers into the scene.
  • refreshHexagons: Drives the continuous motion and evolution of each hexagon on the canvas. Handles redrawing, movement, direction changes, and potential exits.
  • requestAnimationFrame(loop): Initiates the next iteration of the loop, seamlessly creating an animation loop. Utilizes the browser's native requestAnimationFrame for optimal performance.

?? The Eternal Ballet Continues ??

The loop function embodies the heartbeat of your canvas, orchestrating the ongoing performance of hexagons. With each frame, the canvas is refreshed, new hexagons join the dance, and the existing ones gracefully evolve.

Final Output :

Enchanting Hexagons: A Dazzling Display of Mesmerizing Animations with HTML, CSS & JS

Follow for more content ??

????????????????????????????????????

Join the Discord Server ??

?? Discord: Click Here!

Akshat Gupta

Aspiring Web developer

10 个月

Woow....... It's amazing.....Thanks for sharing Stelvin Saji. Do you upload these codes on github ??

回复
Aniket Dandotiya

Pre-Finalite at MITS-DU Gwalior

10 个月

just looking like a wow!!!

要查看或添加评论,请登录

社区洞察

其他会员也浏览了