SVG Path-Drawing With jQuery
by the_voder
HTML
<main>
<svg width="100%" id="svgDrawn" viewBox="-10 0 340 333">
<path id="svgPath" fill="none" stroke="grey" stroke-width="0" d="M20.010,133.545c0,0-21-57,18-67s49-4,65,8
s30,41,53,27s66,4,58,32s-5,44,18,57s22,46,0,45s-54-40-68-16s-40,88-83,48s11-61-11-80s-79-7-70-41" />
</svg>
<div id="poem">
<h2>Title of something</h2>
<p>You declare you see me dimly<br>
through a glass which will not shine,<br>
though I stand before you boldly,<br>
trim in rank and marking time.<br>
You do own to hear me faintly<br>
as a whisper out of range,<br>
while my drums beat out <br>the message
and the rhythms <br>never change. </p>
</div>
</main>
CSS
#poem {
position: absolute;
top: 30%;
left: 20%;
}
#poem h2,
#poem p {
display: none;
}
#svgDrawn {
position: absolute;
margin: 0 auto;
top: -150px;
transform: scale(0.7);
}
JavaScript
// Handle to path element
var path = document.getElementById("svgPath");
// jQuery object from above (saves multiple conversion operations later)
var $path = $(path);
// Get length of path
var pathLength = path.getTotalLength();
// Set dasharray to exact length of path
$path
.attr("stroke-dasharray", pathLength)
.attr("stroke-dashoffset", pathLength)
.attr("stroke-width", 4);
$path
.animate({
"stroke-dashoffset": pathLength / 2
},
2000, function() {
$("#poem h2").fadeIn(1800);
}
)
.delay(1000)
.animate({
"stroke-dashoffset": 0
},
2000, function() {
$("#poem p").fadeIn(1800);
}
);