Animated Hand-Drawn Style Highlight, Underline And Other Annotations With RoughNotation JS

October 19, 2023 by Andreas Wik

RoughNotation JS is a really cool library which lets you spice annotations up, such as underline, highlights and circles, with hand-drawn style lines.

 

Here’s a CodePen I put together:

See the Pen Untitled by Andreas Wik (@andreaswik) on CodePen.

 

Using it is quite straightforward.

First, let’s load the module.

import { annotate } from "https://unpkg.com/rough-notation?module";

 

Then, let’s create a paragraph with and within it a word, wrapped in a span element, that we want to annotate.

<p>Add the <span id="underline-word">carrot</span> to the soup.</p>

 

To create an annotation for this span element, we pass annotate the element and an options object. Finally, to actually make it appear visually, we call .show().

const myElement = document.getElementById('underline-word');
const myAnnotation = annotate(myElement, { type: 'underline' });
myAnnotation.show();

 

Types of annotations

As you can see in the code snippet above, we pass in a type property with the value of underline.

There are 7 different types of annotations you can use.

These are: highlight, circle, box, underline, strike-through, crossed-off and bracket.

 

Additional options – color, animation etc.

So far we have only used the type option, but there are a lot more customization options available.

color is one such option. Just pass it a color, a hex value for example.

const myAnnotation = annotate(myElement, { color: '#ff0000', type: 'underline', });

 

We can also set the width of the stroke with strokeWidth, example:

const myAnnotation = annotate(myElement, { strokeWidth: 3, type: 'underline' });

 

The padding option is also useful if you need the stroke closer to further away from the element.

const myAnnotation = annotate(myElement, { padding: 0, type: 'underline' });

 

You can also enable or disable the animation by setting animation to true or false. By default it’s enabled.

Using animationDuration you can change the duration of the animation from the default 800 milliseconds. Below we set it to 300 milliseconds instead.

const myAnnotation = annotate(myElement, { animationDuration: 300, type: 'underline' });

 

Group of annotations

If you have multiple annotations, you don’t necessarily have to run .show() for every single one. You can use annotationGroup for that. Make sure you import it along with annotation.

import { annotate, annotationGroup } from "https://unpkg.com/rough-notation?module";

 

Then pass annotationGroup all of your annotations in an array and call .show().

const myAnnotationGroup = annotationGroup([firstAnnotation, secondAnnotation, thirdAnnotation]);
myAnnotationGroup.show();

 

Read more and check out the full documentation atΒ https://github.com/rough-stuff/rough-notation.

Have fun!

Share this article

Recommended articles

@awikio