DEV Community

Cover image for ✏️ Drawing sketchy shapes in JavaScript using RoughJS
Benjamin Mock
Benjamin Mock

Posted on

5 1

✏️ Drawing sketchy shapes in JavaScript using RoughJS

RoughJS is a cool library to draw sketchy or hand drawn stuff on the canvas or in svg. For the example I chose svg.

Every time you reload the page, the drawing will look a bit different. This is a very simple example using lines, arcs, circles and rectangles.

I'll post some more examples using RoughJS in the future. So please consider following me to not miss any of the future articles.

<html>
  <head>
    <title>RoughJS</title>
    <script src="https://rawgit.com/pshihn/rough/master/dist/rough.js"></script>
    <style>
      body {
        background: #000;
      }
      svg {
        display: block;
        width: 600px;
        height: 600px;
      }
    </style>
  </head>

  <body>
    <!-- the element we work with-->
    <svg id="svg"></svg>

    <script>
      // get the svg element
      const svg = document.getElementById('svg');
      // we tell roighJS which element we want to use
      const rc = rough.svg(svg);

      // draw the c using lines
      svg.appendChild(rc.line(40, 40, 40, 100, { stroke: 'white' }));
      svg.appendChild(rc.line(40, 40, 60, 40, { stroke: 'white' }));
      svg.appendChild(rc.line(40, 100, 60, 100, { stroke: 'white' }));

      // the o - using a circle of course
      svg.appendChild(
        rc.circle(120, 70, 60, {
          stroke: 'white',
          strokeWidth: 2,
          fill: 'yellow',
          hachureAngle: 60,
          hachureGap: 10,
        })
      );

      // draw the D using an arc
      svg.appendChild(
        rc.arc(180, 70, 60, 60, -Math.PI / 2, Math.PI / 2, true, {
          stroke: 'white',
          strokeWidth: 2,
          fill: 'blue',
          fillStyle: 'solid',
        })
      );

      // draw an E using lines
      svg.appendChild(rc.line(220, 40, 220, 100, { stroke: 'white' }));
      svg.appendChild(rc.line(220, 40, 260, 40, { stroke: 'white' }));
      svg.appendChild(rc.line(220, 100, 260, 100, { stroke: 'white' }));
      svg.appendChild(rc.line(220, 70, 260, 70, { stroke: 'white' }));

      // and putting a border around our artwork using a rectangle
      svg.appendChild(rc.rectangle(10, 10, 280, 120, { stroke: 'white' }));
    </script>
  </body>
</html>

Thanks for reading!

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →