Learn the Basics of Paper.js with Generative Art

In this video we will explore the basics of getting started with the paper.js while having fun with generative art examples. Paper.js is an open source vector graphics scripting framework that runs on top of the HTML5 Canvas. It offers a clean Scene Graph / Document Object Model and a lot of powerful functionality to create and work with vector graphics and bezier curves, all neatly wrapped up in a well designed, consistent and clean programming interface.

Watch the Tutorial on YouTubeGet the Project Cloneable

Inside <head> tag

<script defer src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.12.17/paper-full.min.js"></script>

Inside </body> tag

<script>
function init() {
  const { Path, Color, Line, Circle, Point } = paper;

  const colors = ["#28298A", "#612A87", "#F5D609", "#F17144", "#EF445C"];

  const canvas = document.querySelector("#paper-canvas");
  const regenButton = document.querySelector("#regen-button");

  paper.setup(canvas);

  function main() {
    paper.project.clear();
    // get width and height of our canvas
    let w = canvas.clientWidth;
    let h = canvas.clientHeight;
    let distance = w / 50;

    for (let x = 0; x < w; x += distance) {
      for (let y = 0; y < h; y += distance) {
        // dots(x, y, distance);
        // grid(x, y, distance);
        lines(x, y, distance);
      }
    }
  }
  main();

  function dots(x, y, distance) {
    let point = new Point(x, y);
    let circle = new Path.Circle(point, distance / 4);
    let color = colors[getRandomIndex(colors.length)];
    circle.fillColor = new Color(color);
  }

  function grid(x, y, distance) {
    let lineOne = new Path.Line(new Point(x, y), new Point(x + distance, y));
    lineOne.strokeColor = new Color("#fff");
    let lineTwo = new Path.Line(new Point(x, y), new Point(x, y + distance));
    lineTwo.strokeColor = new Color("#fff");
  }

  function lines(x, y, distance) {
    let r = Math.random();
    let rIndex = getRandomIndex(colors.length);

    if (r < 0.5) {
      // top left to bottom right
      let line1 = new Path.Line(
        new Point(x, y),
        new Point(x + distance, y + distance)
      );
      line1.strokeColor = new Color("#fff");
      line1.strokeWidth = 1;
    } else {
      // bottom left to top right
      let line2 = new Path.Line(
        new Point(x, y + distance),
        new Point(x + distance, y)
      );
      line2.strokeColor = new Color("#fff");
      line2.strokeWidth = 1;
    }
  }

  function getRandomIndex(max) {
    return Math.floor(Math.random() * max);
  }

  function handleRegenButtonClicked() {
    main();
  }

  function handleResize() {
    main();
  }

  regenButton.addEventListener("click", handleRegenButtonClicked);
  window.onresize = handleResize;
}

document.addEventListener("DOMContentLoaded", init)
</script>