JavaScript

Beginner-Friendly! A Complete Guide to Sketching in the Browser with JavaScript and p5.js

This time, we’re introducing the JavaScript library “p5.js,” which allows you to easily draw graphics in the browser, not only for engineers but also for complete beginners. This article is especially useful for those who have just started learning to code, as well as artists and designers.

What is p5.js?

p5.js is a JavaScript library that enables you to easily create graphical expressions on the web. It carries on the spirit of the programming language Processing and reinterprets it for the web.
According to the official website: p5.js, it is positioned as “a coding environment for artists, designers, educators, and beginners.” In other words, even without complex coding knowledge, you can create creative works.

How to Use p5.js Easily

Now, let’s take a look at how to draw using p5.js in the browser. First, load the p5.js library from a CDN (Content Delivery Network). Then, write a simple JavaScript code that allows you to draw circles by just moving your mouse.

Here is a sample JavaScript script that loads the p5.js file from a CDN and draws circles (○) as you move the mouse in the browser.
Here is the sample code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.0/p5.js"></script>

<script type="text/javascript">
function setup() {
  createCanvas(1200, 500);
}

function draw() {
  if (mouseIsPressed) {
    fill(0);
  } else {
    fill(255);
  }
  ellipse(mouseX, mouseY, 80, 80);
}
</script>

 
When this code is executed, black and white circles will be drawn in the browser as you click and move the mouse.

Exploring p5.js Further

p5.js is a beginner-friendly library, but it also offers a variety of features and techniques.
If you want to learn more, be sure to check the “p5.js|get started” section on the official site.

Also, even if you don’t want to set up a programming environment on your PC, the “p5.js Web Editor” allows you to write and run code directly in your web browser, which is extremely convenient.

Sample Demo Page Using the p5.js Library

It might be hard to grasp everything through words alone. So, we’ve prepared a demo page created using p5.js. Please try it out for yourself!

Sample Demo Page Using the p5.js Library

Conclusion

In this article, we introduced the JavaScript library “p5.js,” which can be enjoyed by everyone from beginners to advanced users. If you’re interested in coding but haven’t taken the first step, or if you’re an artist looking to explore creative expression, p5.js is a great tool to start with. We hope this article helps spark your creativity.

 
*If you reuse this content, please do so at your own risk.
Do not reuse the Google Analytics tag inside the demo page’s head tag.