Getting Started with Creative Coding: An Introduction to p5.js

Today, we’ll dive headfirst into the universe of creative coding, with a spotlight on p5.js. One of the most approachable platforms for newcomers to creative coding, p5.js uniquely bridges the gap between simplicity and power, making it an ideal choice for beginners and experts alike.

What is p5.js?

p5.js is a javascript library specifically designed to make coding accessible for artists, designers, educators, beginners, and anyone else who wants to learn and experiment with code in an artist-friendly environment. It’s like a paintbrush for code, helping you to create your interactive masterpiece (or happy little trees if you are a Bob Ross fan).

Why p5.js? The Power of Simplicity

So, why choose p5.js over other creative coding platforms? The answer lies in the simplicity of p5.js. It’s designed to be easy to use, with a syntax that’s intuitive and easy to understand, even if you’re new to coding.

However, don’t let its simplicity fool you. While p5.js is incredibly user-friendly, it’s also incredibly powerful, boasting a broad range of features that can cater to complex projects. From basic shapes and colors to animations, interaction, and even 3D graphics, p5.js has got you covered.

The Power of Community

Another awesome thing about p5.js is its community. With an active and supportive community, you’re never alone on your creative coding journey. You can find a ton of tutorials, examples, and projects from the community that can inspire and guide you along the way. Definitely don’t miss The Coding Train, one of the absolute best places to learn!

Getting Hands-On with p5.js

Talking about p5.js is great, but the real fun begins when we start creating with it. Let’s dive into a simple interactive sketch using p5.js. We’ll use the p5.js web editor, a browser-based coding environment, so no installation is required. Just open it up, and you’re ready to code.

Interactive Circles

In this activity, we’ll create a sketch where circles of different colors appear wherever you click on the canvas. Here’s how to do it:

  1. Open the p5.js web editor.
  2. Inside the setup() function, initialize the canvas size with the following command: createCanvas(windowWidth, windowHeight);.
  3. Change the background color by using background(220); in the setup() function. Doing this here will set the background color once and avoid refreshing it at every frame, thus allowing us to see all the circles we draw.
  4. Now, let’s implement the mousePressed() function. This is a special function in p5.js that automatically gets called whenever a mouse click occurs.
  5. Within the mousePressed() function, use fill(random(255), random(255), random(255)); to set a random color for the circle that we’ll draw. The random(255) part will generate a random value between 0 and 255 for each of the RGB color channels.
  6. Still within the mousePressed() function, use the ellipse() function to draw a circle where the mouse was pressed. Use ellipse(mouseX, mouseY, 50, 50); to draw a circle at the mouse location with a width and height of 50 pixels.
  7. For completeness, include an empty draw() function. While we don’t need it for this specific activity since we’re not continuously updating anything on the canvas, it’s good practice to include it, especially if you plan on adding more interactivity or animation later on.

Your code should look like this:

function setup() {
  createCanvas(windowWidth, windowHeight);
  background(220);
}

function draw() {
  // nothing here (yet)
}

function mousePressed() {
  fill(random(255), random(255), random(255));
  ellipse(mouseX, mouseY, 50, 50);
}

Now, click anywhere on the canvas. A colored circle should appear at your cursor’s location. Here is mine with a bunch of circles, I got a little wild!

Wrapping Up

Congratulations, you’ve just created your first interactive sketch with p5.js! It’s a simple start, but the possibilities with p5.js are endless. As you grow more comfortable with the library, I encourage you to experiment, get creative, and most importantly, have fun. After all, that’s what creative coding is all about.

Resources

Build your own building blocks for WebVR using A-frame

If you’re interested in building virtual reality experiences for the web, then one of the most approachable ways to go about it is to use a framework like A-Frame. A-Frame makes it really easy to get started with WebVR, it’s an active, well-managed project with a vibrant and growing community, and it’s very fun to use and play around with.

What is A-Frame?

A-Frame is a web framework designed to make WebVR content creation easier, faster, and more accessible. A-frame was started by Mozilla, and has been around since mid-2015. From the A-frame documentation:

A-Frame lets you build scenes with just HTML while having unlimited access to JavaScript, three.js, and all existing Web APIs. A-Frame uses an entity-component-system pattern that promotes composition and extensibility. It is free and open source with a welcoming community and a thriving ecosystem of tools and components.

If you’ve never used it at all, here’s a super-minimal “Hello World” example. It uses a declarative HTML-type syntax as seen below:

See the Pen A-Frame super minimal example by Mark Lee (@leemark) on CodePen.

At the top there’s a link to the A-Frame script, then the <a-scene> element encompasses everything in the WebVR scene, the same way that the <body> element encompasses everything the uses sees in a web page.

Inside the scene there is an <a-box> element which makes–you guessed it–a box appear in the scene. The box has attributes that describe how it should appear, including its position within the scene, its rotation, and its color.

The <a-box> element is a built-in primitive provided by A-Frame. The rest of this post is going to focus on how to build your own reusable components that don’t already exist in A-Frame, how to build your own building blocks in a sense. If this is truly your first time using A-Frame I recommend that you play around with it a little bit to get a feel for it.

Here’s a starter CodePen you can fork and play with, or a Glitch project if you prefer (p.s. both CodePen and Glitch are awesome, and if you haven’t used them you should!). Then check out the introductory parts of the documentation especially the Introduction and Getting Started sections, and maybe even go through the Building a Basic Scene guide. Also here’s a great YouTube playlist of A-Frame tutorials.

Build Your Own Components

Once you’re up to speed with building basic scenes using built-in components and primitives like boxes, spheres, cylinders, etc. you will reach a point where you might want to build your own custom components that you can use in your projects, and even share for others in the community to use.

For a simple example, here’s a “clock” component showing the current time. Next we’ll walk through how it’s built, step-by-step.

See the Pen a-frame clock by Mark Lee (@leemark) on CodePen.


hint: click and drag around

Register Your Component

The first thing you need to do is let A-Frame know about your component by registering it. You do this with AFRAME.registerComponent(), as seen below:

AFRAME.registerComponent('clock', {
    // component code goes here 
});

AFRAME.registerComponent() takes two arguments, the first will be the name of your component, and the second is an object that represents your component itself, containing all of its properties and methods.

Component Lifecycle Methods

A-Frame provides a number of lifecycle methods for your component. These are built-in methods that will automatically get called at certain times, like when it is first initialized, or when its properties are changed. This is where you make your component “do stuff”. In this case we’ll be using the init() and tick() lifecycle methods.

  AFRAME.registerComponent('clock', {
    init: function () {
      // this code runs when the component is first initialized  
    },
    tick: function(){
      // this code gets run on each render loop
      // so typically 30 to 60+ times per second
    }  
  });

First, we’ll take a look at init().

Hello World

Here’s how you can create a text element and add it to the scene (add it to the DOM).

See the Pen a-frame hello world component by Mark Lee (@leemark) on CodePen.

One great thing about A-Frame is, if you are a web developer and are used to working with the DOM, everything pretty much works the way you would expect. For example, creating an element, appending it to another element, and adding a text value, as seen below:

// create a new <a-text> element 
this.clockEl = document.createElement('a-text');
// append it to the component's main element
this.el.appendChild(this.clockEl);
// now set the 'value' attribute 
this.clockEl.setAttribute('value', 'Hello World!');

You can now add the Hello World text to the scene with <a-entity clock></a-entity>. Congratulations, you’ve now built your first component!

In the Codepen above I have also given the entity a position since otherwise it would be at the origin (0, 0, 0) position in the same place as the camera, which would make it hard to see.

Passing in properties

What’s the fun in having a reusable component if you’re only going to have one instance of it, or if all instances will be exactly the same? Let’s make it so that we can pass in some properties and customize each instance of the component.

To do that we will use the schema. The schema is an object that defines the properties for your component. In other words, the schema tells A-Frame what properties to expect to be passed in and what data types (or “property types”) those properties will be. It also lets you define default values in case any of those properties aren’t passed in.

schema: {
  position: {type: 'vec3', default: {x: -.75, y: 1.75, z: -1.75}},
  color: {type: 'color', default: '#0f0'},
  font: {type: 'string', default: 'monoid'}
}

This schema is saying that we can expect a position, a color, and a font to potentially be passed in, that the types of these properties will be vec3, color, and string respectively, and then setting a default value for each.

Once they are defined in the schema, we can access each of these properties via the component’s data object, allowing us to easily grab these values and set them for our component instance using setAttribute().

init: function () {
  this.clockEl = document.createElement('a-text');
  this.el.appendChild(this.clockEl); 
//get the position that was passed in, and set it on this instance
  this.clockEl.setAttribute('position', this.data.position);
//get the color that was passed in, and set it on this instance
  this.clockEl.setAttribute('color', this.data.color);
//get the font that was passed in, and set it on this instance
  this.clockEl.setAttribute('font', this.data.font);
  this.clockEl.setAttribute('value', 'Hello World!');
}

Now when you add the component to the A-Frame scene, you will pass in the position, color, and font like so:
<a-entity clock="font: sourcecodepro; color: #191; position: -1 1.5 -.75"></a-entity>

You can see how this all comes together in the Codepen:

See the Pen a-frame hello world component, with schema by Mark Lee (@leemark) on CodePen.

Make time for making time

We’re actually getting pretty close here, now that you know how to register your component, build your component by adding elements to the DOM, use the built-in lifecycle methods, and use schema to define and pass in properties.

Two things still need to be done in order to turn this Hello World example into a working clock component: we have to get the current time, and then update it regularly. First let’s add a getTime() method to our component that will get a JavaScript Date object and return it as a formatted time string.

getTime: function() {
    var d = new Date();
    return d.toLocaleTimeString();
}     

Then we want to use the tick() lifecycle method to call getTime periodically and update the text element accordingly with the current time (tick() will be called every render loop, many times per second).

tick: function(){
    this.clockEl.setAttribute('value', this.getTime());
}

With those last two pieces in place, we’ve got a fully working and reusable a-frame clock component, which you can instantiate like so:

See the Pen a-frame clock by Mark Lee (@leemark) on CodePen.

“But wait,” you say, “what’s all this <a-entity> nonsense!? I want a proper <a-clock> element!”

In that case, what you want to do is register your brand-new component as a primitive.

Extra Credit: Registering a new Primitive

Primitives extend the <a-entity> as a new custom element, allowing us to instantiate our clock using <a-clock>. Here’s how it works:

AFRAME.registerPrimitive('a-clock', {
  // Attaches the 'clock' component by default
  defaultComponents: {
    clock: {}
  },
  // Maps HTML attributes to the component's properties
  mappings: {
    position: 'clock.position',
    font: 'clock.font',
    color: 'clock.color'
  }
});

And here’s the final Codepen, with everything put together, and three <a-clock>s added to the A-Frame scene:

See the Pen a-frame clock as primitive by Mark Lee (@leemark) on CodePen.

Resources & further reading

A New Generation of Campus Maps

Campus Map

“Anytime I feel lost, I pull out a map and stare. I stare until I have reminded myself that life is a giant adventure, so much to do, to see.”
— Angelina Jolie

conf-listing2014 has been a great year for getting out of my comfort zone, and in keeping with that theme, last month I gave my first-ever conference presentation with a couple of amazing colleagues at HighEdWeb 2014 in Portland, Oregon. I wish I could say that I nailed it, but honestly I tried to pack waaaay too much information into a limited amount of time, and was pretty nervous for the first 10 minutes or so. Still, it was well attended, we got some great questions and feedback afterward, and it was an exciting new experience that I would definitely recommend to anyone else looking to push out of their professional or personal comfort zone.

This presentation was about online maps—specifically higher-ed campus maps—and over the past several months I’ve collected a lot of information and resources that I’d like to share, in case it’s helpful to anyone else who is new-ish to online maps. Some of this will apply specifically to people working at colleges and universities, but there’s also some that could be useful to anyone interested in web-based mapping.

Before we jump in:

« here’s a link to the full slide deck ».

Continue reading “A New Generation of Campus Maps”

A better simple slideshow

Looking back in time by 900hp, on Flickr

 

If you don’t have time to do it right, when will you have time to do it over?
— John Wooden

It’s a do-over! This is another fairly basic slideshow, written in javascript, html, and css. This is a dual-purpose project, it’s meant (1) to be something you can drop right into your page and use if you so choose, but it’s also meant (2) as an example/tutorial showing you how to build a simple DIY slideshow from scratch on your own. You can see a couple of demos of the finished product here: http://leemark.github.io/better-simple-slideshow/. Continue reading “A better simple slideshow”

Pulling JSON data from a public data API

“It is a capital mistake to theorize before one has data.” ― Arthur Conan Doyle

The Go Code Colorado crew, photo by Allison Daniell of Stellar Propeller Studio
Go Code Colorado photos by Allison Daniell of Stellar Propeller Studio

I had the opportunity recently to participate in Go Code Colorado, an “apps challenge” (think weekend hackathon + startup pitch competition) meant to make public data more accessible. It was an awesome experience and it got me thinking about government/public data, and how to use it and combine it in ways that can help people.

Here’s a quick example of how to pull data from one such public data source,  the Colorado Business Entity Database.   Basically, anyone starting a new business or forming a business entity in Colorado, whether that be a sole proprietership, partnership, LLC, corporation, etc, has to file documents and register their business with the Secretary of State’s office, and that information becomes public data. What we’re going to do in this example is to use state-provided API to pull a list of current businesses in a particular ZIP code, and list out their names, street addresses, and cities.
Continue reading “Pulling JSON data from a public data API”

A simple DIY responsive image slideshow made with HTML5, CSS3, and JavaScript

Slide Projector by macattck, on Flickr

“It takes half your life before you discover life is a do-it-yourself project.” ― Napoleon Hill

IMPORTANT: I’ve written a new more robust slideshow, along with a code walkthough/tutorial. If you’re looking for a slideshow to use on your own site, it’ll be better and easier to use than this one. Go check it out: http://themarklee.com/2014/10/05/better-simple-slideshow/

A while back I wrote about a technique for building a simple automatically cycling slideshow using CSS animations, no JavaScript required. While that is definitely an interesting technique, it’s also pretty limited in how you can use it. For example, often with an image slideshow rather than just auto-advancing the slides you may want to let the user have control, so they can navigate forwards and backwards through the images at their own pace. These days you also may want a slideshow that’s responsive, so that it will work across a wide range of devices, automatically resize to fit different screen sizes, and maybe even allow some more touch-centric interaction–like swiping to the left or right instead of clicking “previous” and “next” buttons to cycle through the slides.

If this is what you need and you’re just looking for a drop-in solution, there’s no reason to reinvent the wheel, there are some great slideshow options out there already (here are just a few: SwipeJS, SlidesJS). However if you’re more of the do-it-yourself type and you want to custom-build your own to suit your exact needs, or just want to see how it can be done, then it’s pretty easy to get started with just a little bit of HTML, CSS, and JavaScript.
Continue reading “A simple DIY responsive image slideshow made with HTML5, CSS3, and JavaScript”

Geolocation Part II: Building Interactive Maps with Leaflet

“A map does not just chart, it unlocks and formulates meaning; it forms bridges between here and there, between disparate ideas that we did not know were previously connected.”
― Reif Larsen

A couple of weeks ago I wrote about using the Geolocation API, and walked through the minimal code necessary to get the user’s longitude and latitude. Now I want to take it just a step further, and show how to use Leaflet to show the users current location on a map. Continue reading “Geolocation Part II: Building Interactive Maps with Leaflet”