DEV Community

Cover image for How to draw a heart ♥😻❤❣
Paul Ryan
Paul Ryan

Posted on

3

How to draw a heart ♥😻❤❣

Let's go

Drawing an SVG path couldn't be easier, especially with the pathLengthattribute. If you are supporting older browsers, click through to the link to see if your browser is supported.

So let's get an SVG path that we can draw.
Image of heart

Check out the Codepen here which has the SVG included.

The first trick is to add the pathLength property to our path.

<path ..... pathLength="1" />

Doing this makes the animation much easier as we now know the length (i.e. 1). Before you had to calculate the length which was a massive pain!

The next thing we need to do is use stroke-dasharray and stroke-dashoffset. We will set both to 1, this essentially makes our SVG disappear so we can draw it. I don't want to delve into these but you can read about stroke-dashoffset here and stroke-dasharray here. Just know you can set pathLength on any path that you want to draw so once you set it to 1 you can set stroke-dasharray and stroke-dashoffset to 1 everytime!! 😇

So in the CSS panel add the following:

svg path {
  stroke-dasharray: 1;
  stroke-dashoffset: 1;
}

So the heart has disappeared, that is what we want as we are about to draw it back.

We need to create an animation that will animate stroke-dashoffset back to 0.

@keyframes draw {
  from {
    stroke-dashoffset: 1;
  }
  to {
    stroke-dashoffset: 0;
  }
}

One last thing, just add the draw animation to our path.

svg path {
  stroke-dasharray: 1;
  stroke-dashoffset: 1;
  animation: draw 5s linear alternate infinite;
}

Our animation is infinite and also will alternate so it will draw back and forth.

Believe it or not but we are now done. You should have the following:
Heart drawing

Complete pen is here.

Conclusion

Any questions on the above, feel free to contact me on my socials!

💂‍♂️ Insta 👀 Twitter 💬 Github 💭 LinkedIn 💥 Youtube 📭 Website

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (1)

Collapse
 
rem_topx profile image
REM to PX

The converter from REM to PX is a straightforward tool that allows users to switch between the two value measurements easily. The focus is calculating font sizes specified in REM and converting them into pixels PX.

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay