Skip to content

Instantly share code, notes, and snippets.

@richard512
Last active August 29, 2015 14:20
Show Gist options
  • Save richard512/82936e90f6958e1ddc49 to your computer and use it in GitHub Desktop.
Save richard512/82936e90f6958e1ddc49 to your computer and use it in GitHub Desktop.
Text Writing Animation on Canvas via JS. Demo: http://jsbin.com/navawinifi
<canvas width=600></canvas>
<script>
var ctx = document.querySelector("canvas").getContext("2d"),
dashLen = 220, dashOffset = dashLen, speed = 5,
txt = "Loading...", x = 0, i = 0;
ctx.font = "50px Comic Sans MS, cursive, TSCu_Comic, sans-serif";
ctx.lineWidth = 5;
ctx.lineJoin = "round";
ctx.globalAlpha = 0.7;
(function loop() {
ctx.clearRect(x, 0, 60, 150);
ctx.setLineDash([dashLen - dashOffset, dashOffset - speed]); // create a long dash mask
dashOffset -= speed; // reduce dash length
ctx.strokeText(txt[i], x, 100); // stroke letter
if (dashOffset > 0) requestAnimationFrame(loop); // animate
else {
ctx.fillText(txt[i], x, 100); // fill final letter
dashOffset = dashLen; // prep next char
x += ctx.measureText(txt[i++]).width + ctx.lineWidth * Math.random();
if (i < txt.length) requestAnimationFrame(loop);
}
})();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment