# Alex Codes Art > Discover creative coding and generative art at alexcodesart.com. Explore p5.js tutorials and join our community to create stunning digital art. Start your journey today! Public Ghost content for AI and LLM tooling. This file includes a bounded export of public pages first, then recent public posts. Append `.md` to any post or page URL to get the content in Markdown (for example, `/example-post.md`). ## Pages ### About me URL: https://alexcodesart.com/about/ Last updated: 2024-07-09T16:53:36.000Z ![Picture with Alex Postolache and a laptop](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/07/IMG_9406-2.jpg) 🙃 Hey there! That's me! Hey there 👋 I'm Alex, a software engineer living in Amsterdam, The Netherlands. With over a decade of experience as a software engineer, I’ve created websites, mobile apps, video games, and more. Welcome to my creative coding blog, where I talk about coding and art. What you will find here are tutorials about creative coding, generative art, algorithms and techniques. Let's learn to code and create beautiful digital art that speaks to you! # My journey This blog is born from a love for both programming and art. Whether you’re a beginner struggling with coding basics, an experienced programmer curious to learn new techniques or an artist inspired to bring your digital creations to life, I’ve been there too. I know the frustrations of debugging, the challenge of starting new projects, and the desire to make something truly unique. # Why I Started This Blog I was once a beginner, fascinated by the potential of creating art through code but unsure where to start. Over the past decade, I’ve learned that programming is not just about writing code—it’s about expressing ideas and solving problems creatively. This blog is my way of sharing that journey, providing the resources and support I wish I had when I started. Join me as we explore the fusion of creativity and technology, learning and growing together. Discover, create, and be inspired. Let’s make something beautiful! ## Sign up to receive new articles straight to your email Art with code for curious minds Subscribe Email sent! Check your inbox to complete your signup. No spam. Unsubscribe anytime. ### Creative Coding Playground URL: https://alexcodesart.com/creative-coding-playground/ Last updated: 2026-06-20T08:46:15.000Z Welcome to my creative coding playground - a space where I build interactive tools that blend code, music, and generative art. ### Live Projects - [Canvas Generator](https://canvas.alexcodesart.com/?ref=alexcodesart.com) A personalized generative art experience. Answer a few prompts and get a unique artwork generated from your inputs. - [Step Sequencer](https://sequencer.alexcodesart.com/?ref=alexcodesart.com) A browser-based drum sequencer built with Strudel. Create rhythmic patterns, experiment with sound banks, and export your ideas. - [L-Systems](https://alexandru-postolache.github.io/alex-codes-art/l-system/?ref=alexcodesart.com) Generate beautiful fractals using L-systems and turtle graphics. Experiment with rules, angles, and iterations to create intricate procedural patterns. --- I use this page as a hub for all my interactive experiments. As new projects go live, they’ll be added here. If you enjoy this kind of work, check back often, I’m always building something new. ### Creative Coding Roadmap URL: https://alexcodesart.com/creative-coding-roadmap/ Last updated: 2026-07-08T07:34:04.000Z ## Learn p5.js by building generative art, interactive sketches, animations and shaders. ### A free collection of step-by-step tutorials designed to help you grow from your first sketch to advanced creative coding techniques. Programming doesn't have to end with websites and apps. Creative coding combines programming, mathematics and design to create interactive experiences, generative art, animations and visual experiments. Whether you're a software developer discovering your artistic side or an artist curious about programming, this roadmap will guide you from your very first sketch to advanced generative art techniques. > **What you'll learn** > > ✅ Beginner-friendly tutorials > ✅ Hands-on projects > ✅ Interactive demos > ✅ Complete source code > ✅ Real-world creative coding techniques > ✅ Free tutorials with optional premium content --- ## Hi, I'm Alex 👋 I'm a software engineer who discovered creative coding as a way to combine programming with art. On this site I document what I learn while building generative art, interactive sketches and shaders. This roadmap brings together the tutorials I'd recommend if I were teaching someone from scratch. # Why Learn Creative Coding? Creative coding is one of the most rewarding ways to learn programming. Instead of building another to-do app or CRUD project, you'll create artwork, simulations and interactive experiences that are fun to build and exciting to share. Along the way you'll naturally learn: - JavaScript - p5.js - Mathematics for graphics - Animation - Geometry - Algorithms - Generative Art - GLSL Shaders - Creative problem solving My goal isn't just to show you code that works. Every tutorial explains **why** it works, so you can reuse the ideas in your own projects instead of copying solutions. Every tutorial on AlexCodesArt focuses on building something beautiful while explaining the programming concepts behind it. --- # Your Learning Roadmap Think of this page as your learning path. Don't worry about mastering everything at once. Follow the stages in order and you'll gradually build the skills needed for advanced projects. # Stage 1 — Getting Started ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2026/07/artwork--1-.png) **Goal:** You'll build your first interactive sketch and learn the core concepts used throughout the rest of the roadmap. In this stage you'll learn: - What creative coding is - Installing and using p5.js - The canvas - Drawing basic shapes - Colors - Coordinates - Your first animation ### Recommended tutorials [Unleashing Your Imagination: An Introduction to Creative Coding and Generative Art with p5.jsWelcome to the exciting world of creative coding! Whether you’re a seasoned developer or a curious beginner, exploring the realms of generative art through p5.js opens up endless possibilities for artistic expression and computational creativity. In this blog post, we’ll delve into the basics of p5.js,![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/icon/Logo--1--d89ece07-c3f6-4547-9f0f-a3f138028080.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/thumbnail/grid0-1-288ed30d-4023-49a3-90d8-e8916b00ad1e.jpg)](https://alexcodesart.com/unleashing-your-imagination-an-introduction-to-creative-coding-and-generative-art-with-p5-js/) [Getting Started with p5.js: An Introduction to Creative Coding for BeginnersIntroduction to Programming and p5.js Welcome to the world of creative coding with p5.js! Whether you’re an artist, designer, educator, or a complete beginner, p5.js is a powerful JavaScript library that makes coding visual and interactive projects accessible and fun. Let’s dive into the core![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/icon/Logo--1--9ce7be39-084f-445f-9fa4-d158093763a9.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/thumbnail/grid0-14369c39-2475-4871-9d95-da8b8c66912b.jpg)](https://alexcodesart.com/getting-started-with-p5-js-an-introduction-to-creative-coding-for-beginners/) [Create Your First Digital Art with Code: A Step-by-Step GuideLet’s build your first digital art with code. Starting with the Basics As a starting place to write and create your first digital art pieces, I recommend using the official p5.js editor. Once you open the editor, you’ll see the code editor on the left side of![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/icon/Logo--1--9e8a26e5-9284-401d-a958-84064eaf74aa.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/thumbnail/Screenshot_2024-05-31_at_15.41.22-1-618dc2a5-b5e2-49ed-9137-174ddac4aaad.png)](https://alexcodesart.com/create-your-first-digital-artpiece-with-code-a-step-by-step-guide/) --- # Stage 2 — Motion & Animation 0:00 /0:05 1× **Goal:** Bring your artwork to life. You'll learn: - frameCount - Time-based animation - Smooth movement - Easing - Loops - Animation principles ### Recommended tutorials [Create Abstract Art with p5.js: Animate the Sun and WavesHello and welcome back to another exciting tutorial! Today, we’ll dive deeper into creative coding with p5.js and explore some fundamental programming concepts. In this session, we’ll create an abstract art piece featuring a sun and waves, and by the end, we’ll animate both the sun![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/icon/Logo--1--6ae3c6e9-2ccf-46f3-ac63-867cf545cdfb.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/thumbnail/download--17--b2f8395e-48b4-4563-8416-38d252e51835.png)](https://alexcodesart.com/create-abstract-art-with-p5-js-animate-the-sun-and-waves/) [Animating Abstract Art: A Beginner’s Guide to Tweening with p5.jsHello friends! Today, we are diving into the world of creative coding by making a beautiful piece of abstract art and animating it using tweening in p5.js. This tutorial is perfect for coding beginners interested in generative art. First, let’s take a look at the final piece and![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/icon/Logo--1--e7979696-7e14-449e-bf40-789e03de455b.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/thumbnail/0000143-1-6abb294f-df81-47d2-a4f7-8ce62f9cae8d.png)](https://alexcodesart.com/animating-abstract-art-a-beginners-guide-to-tweening-with-p5-js/) --- # Stage 3 — Mathematics for Art ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2026/07/cover-7.png) **Goal:** Learn the math behind beautiful visuals. Don't worry—you don't need to love math. Every concept is explained visually and immediately applied to artwork. You'll discover: - Trigonometry - Polar coordinates - Vectors - Randomness - Perlin Noise - Interpolation - Distance calculations ### Recommended tutorials [Drawing Noisy Circles with p5.js: A Deep Dive into Polar Coordinates and Perlin NoiseIn this creative coding tutorial, we’re building animated noisy circles using p5.js. These aren’t just ordinary circles—they pulse, shift, and morph over time. The motion comes from Perlin noise, and the structure is based on polar coordinates. You can tweak everything from color modes to noise![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/icon/Logo--1--7ab8438e-66b2-40aa-8fcd-4eccae67d419.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/thumbnail/download-5dd3677d-71b7-43f4-ba62-c3c54f7379d0.png)](https://alexcodesart.com/drawing-noisy-circles-with-p5-js-a-deep-dive-into-polar-coordinates-and-perlin-noise/) [Create Stunning Generative Art with Circles in p5.jsWelcome back to another exciting tutorial about creative coding and generative art! Today, we’ll dive into creating a simple composition with concentric circles and some text. In the second part of this tutorial, we’ll use p5.gui.js to create a small graphical interface, allowing us to easily![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/icon/Logo--1--01dd8983-c994-4c57-b1d2-691e27ea76fb.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/thumbnail/download--11--1-9621ad79-265d-4c31-a247-fa2b95d6bec4.png)](https://alexcodesart.com/create-stunning-generative-art-with-circles-in-p5-js/) --- # Stage 4 — Interaction ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2026/07/Screenshot-2026-07-07-at-23.45.32.png) **Goal:** Create interactive experiences. Learn how to make your artwork respond to users. Topics include: - Mouse interaction - Keyboard input - Touch controls - Sliders - Tweakpane - User interfaces ### Recommended tutorials [Building a Step Sequencer with Strudel: Creative Coding Meets Visual Beat-MakingHello friends, and welcome to another creative coding tutorial! In the previous tutorial, we explored Strudel — a browser-based creative coding library that lets you make music with code. We wrote drum patterns, melodies, and layered grooves using just a few lines of JavaScript. If you haven’t read that![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/icon/Logo--1--360db14c-f4db-4d88-b495-7ee4fd590b90.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/thumbnail/Screenshot-2026-04-07-at-10.47.02-28133c91-89a2-421e-9853-7548b9a0e59b.png)](https://alexcodesart.com/building-a-step-sequencer-with-strudel-creative-coding-meets-visual-beat-making/) [Mastering Creative Coding: Building Interactive Radial Strokes with p5.jsHello friends, and welcome to another creative coding tutorial! Today, we’re going to create an interactive piece of digital art using p5.js. You can interact with this artwork by changing parameters in the top right corner, and watch as the digital art transforms in real-time. Getting Started![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/icon/Logo--1--535b3563-8ab0-42d2-ac02-abe8f14641c8.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/thumbnail/radial-strokes--9--97ac944a-ca6b-46e0-965f-958b2c3da5c3.png)](https://alexcodesart.com/mastering-creative-coding-building-interactive-radial-strokes-with-p5-js/) --- # Stage 5 — Generative Art ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2026/07/Screenshot-2026-06-20-at-12.41.25.png) Now things become really fun. You'll start creating artwork that feels organic, procedural and unique every time it runs. Projects include: - Mandalas - Abstract compositions - Pattern generation - Procedural drawing - Creative experiments ### Recommended tutorials [Drawing a Mandala with p5.js: Smooth Lines, Speed-Based Thickness & Tweakpane - Part 1Hello friends, and welcome to another creative coding tutorial! Today we’re going to build a mandala maker in the browser — you drag with the mouse, and every stroke is mirrored and rotated so you get kaleidoscope-like patterns in real time. We’ll wire up symmetry, smoothing, velocity-based![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/icon/Logo--1--876b2777-2ab8-414a-b13b-061ed64ec2fa.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/thumbnail/MandalaBasic--2--e33409ef-01a2-495e-9326-2f7e5ba44caa.png)](https://alexcodesart.com/drawing-a-mandala-with-p5-js-smooth-lines-speed-based-thickness-tweakpane-part-1/) [Building an Interactive Generative Art with p5.js, Tweakpane, and Watercolor EffectsIn the previous tutorial, we looked at how we can build an interactive piece of digital art using p5.js and we talked a bit about the math behind it. Mastering Creative Coding: Building Interactive Radial Strokes with p5.jsHello friends, and welcome to another creative coding tutorial! Today, we’![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/icon/Logo--1--db65fa21-a2f9-4e4a-94d2-24bb7e678312.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/thumbnail/artwork--6--aa96c779-6bfc-4035-af5c-8433e8fc1a62.png)](https://alexcodesart.com/building-an-interactive-generative-art-with-p5-js-tweakpane-and-watercolor-effects/) --- # Stage 6 — Creative Algorithms ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2026/07/Screenshot-2026-04-25-at-12.22.07.png) This is where programming and art truly meet. You'll explore algorithms used by artists and game developers alike. Topics include: - L-Systems - Metaballs - Flow Fields - Particle Systems - Circle Packing - Cellular Automata - Recursive drawing - Procedural generation ### Recommended tutorials [Create Animated Metaballs with Shaders in p5.js — A Creative Coding TutorialHey there and welcome to another tutorial about creative coding and generative art. In this tutorial we will look at what SDFs are and how we can use them to create metaballs. Metaballs are a classic technique in generative art used to create organic, fluid shapes that morph and merge![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/icon/Logo--1--1a19b6fb-504c-4407-8286-3540dc81d586.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/thumbnail/download--2--1-1-db75ca8f-57e0-4e29-8984-0a692dcd7409.png)](https://alexcodesart.com/create-animated-metaballs-with-shaders-in-p5-js-a-creative-coding-tutorial/) [Drawing Fractals with L-Systems in p5.js: A Creative Coding TutorialHello friends, and welcome to another creative coding tutorial! Today, we’re going to draw beautiful fractal forms with L-systems and p5.js. L-systems are one of those beautiful creative coding ideas where a tiny bit of text can grow into branches, curves, triangles, snowflakes, and all kinds![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/icon/Logo--1--9ffba885-d9a7-435e-a118-f2d556c23e43.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/thumbnail/download--1--1-cee4b887-7911-46b5-a34e-4c5059455a1b.png)](https://alexcodesart.com/drawing-fractals-with-l-systems-in-p5-js-a-creative-coding-tutorial/) --- # Stage 7 — GLSL & Shaders ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2026/07/Screenshot-2026-07-07-at-23.51.19.png) Ready to unlock the GPU? Shaders let you create visuals that would be impossible or inefficient using standard JavaScript alone. You'll learn: - Fragment shaders - Vertex shaders - Distortion effects - Liquid Glass - Lighting - Noise in GLSL - GPU rendering - Advanced visual effects ### Recommended tutorials [Create Animated Metaballs with Shaders in p5.js — A Creative Coding TutorialHey there and welcome to another tutorial about creative coding and generative art. In this tutorial we will look at what SDFs are and how we can use them to create metaballs. Metaballs are a classic technique in generative art used to create organic, fluid shapes that morph and merge![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/icon/Logo--1--3caa7aea-7fc7-481c-b5be-c3e2d73e6cbc.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/thumbnail/download--2--1-1-844c72aa-1c4d-433a-9ad2-56648a7c76ad.png)](https://alexcodesart.com/create-animated-metaballs-with-shaders-in-p5-js-a-creative-coding-tutorial/) --- # Stage 8 — Build Real Projects Learning is most effective when you create complete projects. Throughout your journey you'll build artwork such as: - 🌸 Mandalas - 💧 Metaballs - 🎨 Watercolor Effects - 🌿 L-System Trees - 🌊 Shader Effects - ✨ Interactive Sketches - 🌀 Procedural Patterns - 🎵 Audio Visualizations These projects combine multiple concepts and will help you develop your own artistic style. --- # Join the Journey Every few weeks I publish new tutorials, creative coding experiments and behind-the-scenes articles about building generative art with JavaScript and p5.js. If you're interested in combining programming and creativity, I'd love to have you along for the journey. Subscribe below and never miss a new tutorial. It's free! ## Sign up for Alex Codes Art Art with code for curious minds Subscribe Email sent! Check your inbox to complete your signup. No spam. Unsubscribe anytime. --- # Ready? Start with **Stage 1** and build your first creative coding sketch. By the time you reach the final stages, you'll be creating artwork powered by mathematics, algorithms and shaders and you'll understand exactly how it works. Happy coding! 🎨💻 ## Posts ### Drawing a Mandala with p5.js: Web MIDI & Tempo-Driven Motion - Part 3 URL: https://alexcodesart.com/drawing-a-mandala-with-p5-js-web-midi-tempo-driven-motion-part-3/ Last updated: 2026-08-28T08:11:04.000Z Hello and welcome back to another exciting tutorial about creative coding and generative art! In part 1 we built a symmetrical mandala with smoothing, speed-based thickness, and Tweakpane. [Drawing a Mandala with p5.js: Smooth Lines, Speed-Based Thickness & Tweakpane - Part 1Hello friends, and welcome to another creative coding tutorial! Today we’re going to build a mandala maker in the browser — you drag with the mouse, and every stroke is mirrored and rotated so you get kaleidoscope-like patterns in real time. We’ll wire up symmetry, smoothing, velocity-based![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/icon/Logo--1--19a26135-207d-4b78-bef5-b71a3cab4bcf.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/thumbnail/MandalaBasic--2--ba67a009-c073-4cd8-b9d9-451a455906a2.png)](https://alexcodesart.com/drawing-a-mandala-with-p5-js-smooth-lines-speed-based-thickness-tweakpane-part-1/) In part 2 we added fading trails, draw-with-keyboard auto-draw motion, and parallel colored lines on keys `1`–`9`. [Drawing a Mandala with p5.js: Fading Trails, Curvy Keys & Multi-Line Color - Part 2Hello and welcome back to another exciting tutorial! In part 1 we built a symmetrical mandala with smoothing, speed-based thickness, and Tweakpane. Today we’re leveling up that same foundation with three ideas: 1\. Fading trails — we remember recent segments and redraw them with transparency so older strokes gently![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/icon/Logo--1--b770f343-45f3-44d2-8d97-41604ddab30a.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/thumbnail/Screenshot-2026-06-20-at-12.41.25-4046b6a2-abae-4c32-99b6-248cd8718e68.png)](https://alexcodesart.com/drawing-a-mandala-with-p5-js-smooth-lines-speed-based-thickness-tweakpane-part-1-2/) Today we're finishing the series with three big ideas: 1. **Tempo-driven motion** — auto-draw strokes on `C` and digit keys that move with a BPM clock, including pauses and subdivisions. 2. **Web MIDI** — connect a drum pad or keyboard and every note spawns its own wandering voice into the mandala. 3. **Two MIDI modes** — **Auto-draw** maps pitch to color and spawn radius, while **Drums** maps General MIDI drum families to fixed rings on the mandala. This tutorial is perfect if you've followed parts 1 and 2, or you're comfortable with `createGraphics()` and want to explore browser MIDI in visual art. By the end of this article, you will: - drive auto-draw lines from a tempo clock with beat phases, pauses, and subdivisions - connect hardware through the [Web MIDI API](https://developer.mozilla.org/en-US/docs/Web/API/Web%5FMIDI%5FAPI?ref=alexcodesart.com) with `navigator.requestMIDIAccess()` - simulate drum hits from the QWERTY keyboard when no pad is plugged in - spawn polyphonic MIDI voices that reuse the same auto-draw motion as keys `1`–`9` - switch between pitch-based and drum-family MIDI mapping - keep MIDI logic separate in a `midiEngine` module so the sketch stays readable Let's play around with it here before we jump into the tutorial _This post is for subscribers only._ ### Drawing a Mandala with p5.js: Fading Trails, Curvy Keys & Multi-Line Color - Part 2 URL: https://alexcodesart.com/drawing-a-mandala-with-p5-js-smooth-lines-speed-based-thickness-tweakpane-part-1-2/ Last updated: 2026-06-26T16:19:55.000Z Hello and welcome back to another exciting tutorial! In [part 1](https://alexcodesart.com/drawing-a-mandala-with-p5-js-smooth-lines-speed-based-thickness-tweakpane-part-1/) we built a symmetrical mandala with smoothing, speed-based thickness, and [Tweakpane](https://alexcodesart.com/drawing-a-mandala-with-p5-js-smooth-lines-speed-based-thickness-tweakpane-part-1/). Today we're leveling up that same foundation with three ideas: 1. **Fading trails** — we remember recent segments and redraw them with transparency so older strokes gently disappear. 2. **Curvy drawing** — hold **`C`** (when enabled) and the stroke wanders on its own using [**noise()**](https://p5js.org/reference/?ref=alexcodesart.com#/p5/noise) and a little sine pulse, release the button stop. 3. **Multi-line keys** — hold **`1`** through **`9`** at the same time for parallel wandering lines, each with its own color in the panel. This tutorial is perfect if you've followed part 1 or you're comfortable with `createGraphics()` and want to explore history, keyboard input, and **Perlin-style motion**. By the end of this article, you will: - store stroke history in an array and **fade** older segments by **alpha** and age - toggle **fade** vs **immediate** drawing so you can compare behaviors - drive a stroke from **noise** \+ **trigonometry** for organic curvy motion - spawn **multiple independent paths** with **`keyIsDown()`** and **digit keys 1–9** - keep colors organized with a **`multiLineColors`** object and Tweakpane pickers Don't miss any new posts — become a member for free! It really helps me out, and I'd love to have you along. Thanks! Let's dive in. _This post is for subscribers only._ ### Drawing a Mandala with p5.js: Smooth Lines, Speed-Based Thickness & Tweakpane - Part 1 URL: https://alexcodesart.com/drawing-a-mandala-with-p5-js-smooth-lines-speed-based-thickness-tweakpane-part-1/ Last updated: 2026-06-16T14:27:55.000Z Hello friends, and welcome to another creative coding tutorial! Today we're going to build a **mandala maker** in the browser — you drag with the mouse, and every stroke is mirrored and rotated so you get kaleidoscope-like patterns in real time. We'll wire up **symmetry**, **smoothing**, **velocity-based stroke thickness**, and **colors**, all tweakable from a small [**Tweakpane**](https://tweakpane.github.io/docs/?ref=alexcodesart.com) panel. This tutorial is perfect for beginners in creative coding who are curious about interactive drawing and a gentle intro to transforms in p5.js. By the end of this article, you will: - understand how **radial symmetry** works by rotating and mirroring each stroke around the center - smooth mouse input with **`lerp()`** so lines feel less jittery - map **drawing speed** to **stroke weight** with **`map()`** and **`lerp()`** - add [**createGraphics()**](https://p5js.org/reference/p5/createGraphics/?ref=alexcodesart.com) so we draw into an off-screen buffer and composite it each frame - expose settings with **Tweakpane** folders for Motion and Colors Before we dive into the code and the logic behind it, let's see what we are going to create and play around with it 😄 Let's dive in. _This post is for subscribers only._ ### Drawing Fractals with L-Systems in p5.js: A Creative Coding Tutorial URL: https://alexcodesart.com/drawing-fractals-with-l-systems-in-p5-js-a-creative-coding-tutorial/ Last updated: 2026-06-26T16:30:51.000Z Hello friends, and welcome to another creative coding tutorial! Today, we’re going to draw beautiful fractal forms with **L-systems** and p5.js. L-systems are one of those beautiful creative coding ideas where a tiny bit of text can grow into branches, curves, triangles, snowflakes, and all kinds of organic-looking structures. We’ll start with a small string, rewrite it again and again, and then use turtle graphics to draw the result on the canvas. By the end of this article, you will: - understand what an L-system is - learn how to expand an axiom with rewrite rules - draw the generated string with turtle graphics - fit the final drawing nicely on the canvas - animate the fractal as it appears line by line Before you start this tutorial, consider signing up to get future articles like this sent straight to your inbox. Thanks! ## Sign up for Alex Codes Art Art with code for curious minds Subscribe Email sent! Check your inbox to complete your signup. No spam. Unsubscribe anytime. Let’s dive in. But first, let's play around with what we are going to create by the end of this tutorial, by tweaking the controls from the left side of the screen (visible on the website only). --- ## What Is an L-System? An **L-system**, short for **Lindenmayer system**, is a way to describe growth using text rules. We begin with an initial word called an **axiom**. Then we apply a set of replacement rules over and over. Each round is called an **iteration**. Here is a tiny example: ``` Axiom: F Rule: F=F+F-F ``` After one iteration, `F` becomes `F+F-F`. After another iteration, every `F` gets replaced again: ``` F+F-F ``` becomes: ``` F+F-F+F+F-F-F+F-F ``` This looks like a strange little sentence, but we can turn it into drawing instructions: - `F` means “move forward and draw a line” - `+` means “turn right” - `-` means “turn left” That’s the core idea. We grow a string, then we draw it. You’re not placing every branch by hand — you’re designing a system that grows the drawing for you. ## What We’re Building We’re going to build a p5.js sketch that: - starts from an axiom - expands that axiom with rewrite rules - turns the final string into turtle graphics commands - stores those commands as line segments - scales and centers the result on the canvas - animates the drawing one segment at a time The finished sketch uses the classic fractal plant L-system, but the same code can also draw Koch curves, Sierpinski triangles, dragon curves, and many other rule-based structures. That’s the magic of generative art: small textual changes can create very different visual results. ## Defining Our L-System Let’s start with the rules for a classic fractal plant. ``` const axiom = 'X'; const rulesText = `X=F+[[X]-X]-F[-FX]+X F=FF`; const iterations = 6; const angle = 25; const drawSpeed = 40; ``` Here’s what each value means: - `axiom` — the starting string. - `rulesText` — the replacement rules, one per line. - `iterations` — how many times we apply the rules. - `angle` — how far the turtle turns. - `drawSpeed` — how many line segments we reveal per frame. The plant rule is especially fun because it uses brackets: `[` and `]`. Those symbols let the turtle save and restore its position, which is how we get branching structures. Nice! ## Parsing the Rules Our rules are written as plain text, one rule per line: ``` X=F+[[X]-X]-F[-FX]+X F=FF ``` We need to turn this text into a JavaScript object. ```javascript function parseRules(text) { const rules = {}; const lines = text.split('\n'); for (const line of lines) { const t = line.trim(); if (!t || t.startsWith('#')) continue; const eq = t.indexOf('='); if (eq <= 0) continue; const key = t.slice(0, eq).trim(); const val = t.slice(eq + 1).trim(); if (key.length) rules[key] = val; } return rules; } ``` Here’s what happens: - `split('\n')` breaks the text into separate lines. - `trim()` removes extra spaces. - Empty lines and comment lines are ignored. - `indexOf('=')` finds where the left side ends and the right side begins. - `rules[key] = val` stores the replacement. So this: ``` F=FF X=F+X ``` becomes this: ``` { F: 'FF', X: 'F+X' } ``` Now our sketch can understand the text rules we defined at the top of the file. ## Expanding the L-System Next, we need a function that starts with an axiom and applies the rules several times. ```javascript function expand(axiom, rules, iterations) { let s = axiom; const keys = Object.keys(rules).sort((a, b) => b.length - a.length); for (let n = 0; n < iterations; n++) { let next = ''; for (let i = 0; i < s.length; ) { let matched = false; for (const k of keys) { if (s.startsWith(k, i)) { next += rules[k]; i += k.length; matched = true; break; } } if (!matched) { next += s[i]; i += 1; } } s = next; } return s; } ``` Let’s unpack it: - `s` stores the current string. - `keys` stores all rule names, sorted from longest to shortest. - For each iteration, we build a new string called `next`. - At each position, we check if one of the rule keys matches. - If a rule matches, we add its replacement. - If no rule matches, we keep the original character. That last part is important. Symbols like `+`, `-`, `[`, and `]` usually do not have rewrite rules. They pass through unchanged so they can be used later by the turtle. This function is where the growth happens. A small axiom can become thousands of drawing commands after only a few iterations. ## Turtle Graphics Now we have a generated string. Time to draw it. We’ll use **turtle graphics**, which is a friendly way to think about drawing. Imagine a tiny turtle standing on the canvas. It has: - an `x` position - a `y` position - a heading, which means the direction it is facing Then we feed it commands: - `F` or `G` — move forward and draw - `f` or `g` — move forward without drawing - `+` — turn one way - `-` — turn the other way - `|` — turn around - `[` — save the current position and heading - `]` — restore the last saved position and heading This is perfect for L-systems because the generated string is already a list of instructions. ## Building Line Segments Instead of drawing immediately, we’ll convert the string into an array of line segments. This makes animation easier because we can draw the first few segments, then a few more, then a few more. ```javascript function buildSegments(str, angleDeg, stepLen, startX, startY, startHeading) { const segs = []; const stack = []; let x = startX; let y = startY; let heading = startHeading; const rad = (angleDeg * Math.PI) / 180; for (let i = 0; i < str.length; i++) { const c = str[i]; if (c === 'F' || c === 'G') { const nx = x + stepLen * Math.cos(heading); const ny = y + stepLen * Math.sin(heading); segs.push({ x1: x, y1: y, x2: nx, y2: ny, depth: stack.length }); x = nx; y = ny; } else if (c === 'f' || c === 'g') { x += stepLen * Math.cos(heading); y += stepLen * Math.sin(heading); } else if (c === '+') { heading += rad; } else if (c === '-') { heading -= rad; } else if (c === '|') { heading += Math.PI; } else if (c === '[') { stack.push({ x, y, heading }); } else if (c === ']') { const st = stack.pop(); if (st) { x = st.x; y = st.y; heading = st.heading; } } } return segs; } ``` Here’s how it works: - `segs` stores all line segments. - `stack` stores saved turtle states for branching. - `heading` is measured in radians, because `Math.sin()` and `Math.cos()` use radians. - For `F` and `G`, we calculate a new point and store a line from the old point to the new point. - For `f` and `g`, we move without storing a line. - For `+` and `-`, we rotate the turtle. - For `[` we save the current state. - For `]` we go back to the last saved state. The small formulas: ``` nx = x + stepLen * cos(heading) ny = y + stepLen * sin(heading) ``` mean “walk forward in the direction we’re currently facing.” If that feels new, don’t worry. You can think of `cos()` as controlling the horizontal movement and `sin()` as controlling the vertical movement. ## Fitting the Drawing on the Canvas Different L-systems create different shapes. Some grow upward like plants. Some spread sideways. Some curl into squares or triangles. So before we draw the final version, we measure the generated segments. ```javascript function boundsOfSegments(segs) { if (!segs.length) return { minX: 0, minY: 0, maxX: 1, maxY: 1 }; let minX = Infinity; let minY = Infinity; let maxX = -Infinity; let maxY = -Infinity; for (const s of segs) { minX = Math.min(minX, s.x1, s.x2); minY = Math.min(minY, s.y1, s.y2); maxX = Math.max(maxX, s.x1, s.x2); maxY = Math.max(maxY, s.y1, s.y2); } return { minX, minY, maxX, maxY }; } ``` This function finds the smallest rectangle that contains the whole drawing. Then we use that rectangle to scale and center the final result: ```javascript function recompute() { const rules = parseRules(rulesText); const str = expand(axiom, rules, iterations); lastStringLen = str.length; let temp = buildSegments(str, angle, 1, 0, 0, -Math.PI / 2); const b = boundsOfSegments(temp); const w = width - 40; const h = height - 40; const bw = b.maxX - b.minX || 1; const bh = b.maxY - b.minY || 1; const scale = Math.min(w / bw, h / bh) * 0.95; const cx = (b.minX + b.maxX) / 2; const cy = (b.minY + b.maxY) / 2; const ox = width / 2 - cx * scale; const oy = height / 2 - cy * scale; segments = buildSegments(str, angle, scale, ox, oy, -Math.PI / 2); needsRecompute = false; } ``` In this function we: - parse the rules - expand the L-system string - store the string length in `lastStringLen` - build temporary segments with a step length of `1` - measure the bounds - calculate a scale that fits inside the canvas - calculate an offset that centers the drawing - build the final segments using the real scale and offset This is why the dragon curve, Sierpinski triangle, and plant can all share the same canvas without flying offscreen. Almost there! ## Setting Up p5.js Now let’s create the p5.js canvas and prepare the line segments. ```javascript let segments = []; let segIndex = 0; let lastStringLen = 0; let needsRecompute = true; function setup() { createCanvas(600, 600); pixelDensity(3); recompute(); } ``` Let’s break this down: - `segments` stores the line segments we draw. - `segIndex` tracks how much of the drawing has been animated. - `lastStringLen` stores the generated string length, which is useful while experimenting. - `needsRecompute` tells us when the line segments should be rebuilt. - [createCanvas()](https://p5js.org/reference/p5/createCanvas/?ref=alexcodesart.com) creates the p5.js canvas. - `pixelDensity()` makes the drawing look crisp on high-resolution screens. - `recompute()` builds the first set of line segments before we start drawing. If you are new to p5.js, [setup()](https://p5js.org/reference/p5/setup/?ref=alexcodesart.com) runs once when the sketch starts. It is the perfect place to create the canvas, set the pixel density, and prepare the first drawing. ## Drawing the Fractal The `draw()` function is where the sketch comes alive. In p5.js, `draw()` runs again and again, usually around 60 times per second. ```javascript function draw() { if (needsRecompute) recompute(); background(35, 38, 58); const target = Math.min(segIndex + drawSpeed, segments.length); strokeWeight(max(1, width / 480)); for (let i = 0; i < target; i++) { const s = segments[i]; stroke(255, 186, 6, 230); line(s.x1, s.y1, s.x2, s.y2); } if (target < segments.length) { segIndex = target; } } ``` Here’s what happens: - If something changed, `recompute()` rebuilds the L-system. - [background()](https://p5js.org/reference/p5/background/?ref=alexcodesart.com) clears the canvas with the background color. - `drawSpeed` controls how many segments we reveal per frame. - `target` is the current number of visible segments. - The `for` loop draws every visible segment with [line()](https://p5js.org/reference/p5/line/?ref=alexcodesart.com). - `segIndex` increases until the full drawing is visible. The animation is very simple, but it makes a huge difference. Instead of instantly seeing a finished fractal, we can watch the system draw itself. Math magic! Great work so far. ## Why This Matters for Creative Coding L-systems are a wonderful reminder that creative coding is often about rules, not individual marks. We do not draw every branch of the plant. We do not place every side of the triangle. We describe a grammar, then let the system unfold. That is the same idea behind many generative art techniques: the artist designs the behavior, and the code produces the final image. Every parameter becomes a tweak into a different visual. ## Experiment and Explore You can make this art your own by: - Changing the angle from `25` to `20`, `30`, or `45` - Increasing and decreasing the iteration count - Editing the plant rule and adding more `[` and `]` branches - Trying a new axiom like `F+F+F+F` - Changing the stroke color from yellow to another palette - Slowing the draw speed so the structure appears more gradually - Creating another L-system by changing `axiom`, `rulesText`, `iterations`, and `angle` You might be surprised how quickly new patterns start to emerge. You can find the full source code here: [alex-codes-art/l-system at main · alexandru-postolache/alex-codes-artArt with code for curious minds. Contribute to alexandru-postolache/alex-codes-art development by creating an account on GitHub.![](https://static.ghost.org/v5.0.0/images/link-icon.svg)GitHubalexandru-postolache![](https://opengraph.githubassets.com/59f951b0f6ad876933d9506183ebd216d1c7311a3fd319b8bc6bc8b1042c7e47/alexandru-postolache/alex-codes-art)](https://github.com/alexandru-postolache/alex-codes-art/tree/main/l-system?ref=alexcodesart.com) --- ## Wrapping Up Thank you for following along with this tutorial! If you have any questions, feedback, or just want to share your own creations, please feel free to leave a comment below. I’ll make sure to respond and help you out as best as I can. Stay connected for more exciting tutorials and creative coding tips by subscribing to this blog. I really appreciate it! Happy coding, and see you in the next tutorial! Want to stay updated with new articles? Just hit subscribe — it’s completely free, and I’d really appreciate the support. Thanks a lot! ## Sign up for Alex Codes Art Art with code for curious minds Subscribe Email sent! Check your inbox to complete your signup. No spam. Unsubscribe anytime. ### Building a Step Sequencer with Strudel: Creative Coding Meets Visual Beat-Making URL: https://alexcodesart.com/building-a-step-sequencer-with-strudel-creative-coding-meets-visual-beat-making/ Last updated: 2026-06-26T16:31:39.000Z Hello friends, and welcome to another creative coding tutorial! In the [previous tutorial](https://alexcodesart.com/making-music-with-code-a-beginners-guide-to-strudel/), we explored Strudel — a browser-based creative coding library that lets you make music with code. We wrote drum patterns, melodies, and layered grooves using just a few lines of JavaScript. If you haven't read that tutorial yet, I recommend checking it out first: [Making Music with Code: A Beginner’s Guide to StrudelHello friends, and welcome to another creative coding tutorial! Most of the time on this blog we explore generative art and creative coding with visuals — using tools like p5.js to draw shapes, animate patterns, or generate abstract compositions. But code isn’t limited to images. It can also generate![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/icon/Logo--1--5.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/thumbnail/strudel-1.png)](https://alexcodesart.com/making-music-with-code-a-beginners-guide-to-strudel/) Today, we're going to take things further. Instead of writing Strudel code by hand, we're going to build a **step sequencer** — a visual interface where you click on a grid to create drum patterns, and the app generates and plays Strudel code for you behind the scenes. By the end of this article, you will: - understand what a step sequencer is and how it works - see how a clickable grid translates into Strudel patterns - learn how Strudel functions like `s()`, `.beat()`, `.bank()`, and `stack()` power the sequencer - understand how the UI and code work together to produce music If you've been enjoying creative coding with visuals, this project bridges two worlds: visual interfaces and algorithmic music. You can find the live step sequencer here, have a look and play around with it: [Strudel Step Sequencer![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/icon/favicon-4.ico)Alex Codes Art![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/thumbnail/logo-horizontal-2.png)](https://sequencer.alexcodesart.com/?ref=alexcodesart.com) You can find a link to the source code of this project at the end of the article. Before you start this tutorial, consider signing up to get future articles like this sent straight to your inbox. ## Sign up for Alex Codes Art Art with code for curious minds Subscribe Email sent! Check your inbox to complete your signup. No spam. Unsubscribe anytime. Let's dive in. --- ## What Is a Step Sequencer? A step sequencer is one of the oldest and most intuitive tools in electronic music. The idea is simple: You have a grid. Each row represents a different instrument — bass drum, snare, hi-hat. Each column represents a moment in time — a step. You click on a cell to activate it. When the sequencer plays, it moves through the columns left to right, triggering the active instruments at each step. Think of it like a grid of switches. Each switch tells the system: "play this sound at this moment." Classic drum machines like the Roland TR-808 and TR-909 popularized this approach. Now, we're building the same concept in the browser — powered by Strudel. --- ## How Our Step Sequencer Works Our step sequencer is a small vanilla JavaScript app that connects a visual grid to Strudel's pattern engine. Here's what happens when you interact with it: 1. You see a grid of rows (instruments) and columns (steps) 2. You click on steps to activate them 3. When you press play, the app reads the grid and builds Strudel patterns 4. Strudel plays those patterns as sound The entire app is built with three files: `index.html`, `main.js`, and `main.css`. No frameworks, no build tools — just code and a creative coding library. Let's break down each part. --- ## Loading Strudel in the Browser The first step is loading Strudel itself. We include it directly from a CDN: ```html ``` This gives us access to all of Strudel's functions — `s()`, `stack()`, `hush()`, and more — as global JavaScript functions. Next, we initialize Strudel and load drum machine samples: ```javascript initStrudel({ prebake: () => loadSamples() }); async function loadSamples() { const ds = "https://raw.githubusercontent.com/felixroos/dough-samples/main/"; return Promise.all([ samples(`${ds}/tidal-drum-machines.json`), ]); } ``` The `initStrudel()` function sets everything up. The `prebake` option tells Strudel to load our samples before anything else — in this case, a collection of classic drum machine sounds from machines like the Roland TR-909, TR-808, LinnDrum, and many more. Once this runs, we have a library of drum sounds ready to play with code. --- ## Building the Grid: Instruments and Steps The heart of the step sequencer is the `StepSequencer` class. When it initializes, it creates the grid. Each instrument gets a row: ```javascript this.instruments = ["hh", "oh", "sd", "bd"]; ``` These abbreviations map to drum sounds that Strudel understands: - `bd` → Bass Drum - `sd` → Snare Drum - `hh` → Hi-Hat - `oh` → Open Hi-Hat The number of columns (steps) depends on the time signature. In 4/4 time, we get 16 steps — four beats, with four subdivisions each: ```javascript this.measure = 4; this.stepsPerBeat = 4; this.stepsPerCycle = this.measure * this.stepsPerBeat; // 16 ``` For each instrument, the app creates a row of clickable step cells: ```javascript for (let i = 0; i < this.stepsPerCycle; i++) { const step = document.createElement('div'); step.classList.add('step', `step-${i}`); step.addEventListener('click', () => this.toggleStep(instrument, i)); stepContainer.appendChild(step); } ``` When you click a step, it toggles an `active` class on that cell: ```javascript toggleStep(instrument, step) { const stepElement = this.container.querySelector( `div.instrument-row.${instrument} div.step.step-${step}` ); stepElement.classList.toggle('active'); } ``` That's it. The state of the entire pattern lives in the DOM — each cell is either active or not. There is no separate data model. The grid *is* the data. This keeps things simple. When it's time to play, the app reads the grid directly to figure out which steps are on. --- ## From Clicks to Code: How the Grid Becomes Strudel This is where things get interesting. When you press play, the step sequencer needs to translate the visual grid into something Strudel can understand. Here's the `play()` method — the core of the entire app: ```javascript play() { hush(); const patterns = this.instruments.map(instrument => { const steps = this.container.querySelectorAll( `div.instrument-row.${instrument} div.step` ); const activeBeats = Array.from(steps) .map((step, i) => step.classList.contains('active') ? i : null) .filter(beat => beat !== null) .join(','); return s(instrument) .beat(activeBeats || '-', this.stepsPerCycle) .bank(this.bank) .cpm(this.bpm); }); this.patternStack = stack(...patterns); this.patternStack.play(); } ``` Let's break this down step by step. ### Step 1: Silence Everything ```javascript hush(); ``` Before starting a new pattern, we call `hush()` — a Strudel function that stops all currently playing sounds. This ensures we always start fresh. ### Step 2: Read the Grid For each instrument, we look at every step in its row and collect the indices of the active ones: ```javascript const activeBeats = Array.from(steps) .map((step, i) => step.classList.contains('active') ? i : null) .filter(beat => beat !== null) .join(','); ``` So if you activate steps 0, 4, 8, and 12 on the bass drum row, `activeBeats` becomes the string `"0,4,8,12"`. ### Step 3: Build a Strudel Pattern This is where the visual clicks become Strudel code: ```javascript return s(instrument) .beat(activeBeats || '-', this.stepsPerCycle) .bank(this.bank) .cpm(this.bpm); ``` Let's unpack each function: - `**s(instrument)**` — Selects a sound. `s("bd")` means "use the bass drum sample." - `**.beat(activeBeats, stepsPerCycle)**` — This is the rhythm function. It takes a comma-separated list of step indices and the total number of steps in a cycle. So `.beat("0,4,8,12", 16)` means "play on steps 0, 4, 8, and 12 out of 16 total steps." If no steps are active, we pass `'-'` which means silence. - `**.bank(this.bank)**` — Selects the sample bank. For example, `"RolandTR909"` uses sounds from the classic TR-909 drum machine. - **`.cpm(this.bpm)`** — Sets the tempo in cycles per minute. ### Step 4: Layer All Instruments Finally, we combine all instrument patterns with `stack()`: ```javascript this.patternStack = stack(...patterns); this.patternStack.play(); ``` `stack()` tells Strudel to play all patterns simultaneously — just like layering tracks in a music production app. --- ## A Practical Example Let's say you build this pattern on the grid: - Hi-Hat: `0, 2, 4, 6, 8, 10, 12, 14` - Snare: `4, 12` - Bass Drum: `0, 8` Behind the scenes, the step sequencer generates the equivalent of this Strudel code: ```javascript stack( s("hh").beat("0,2,4,6,8,10,12,14", 16).bank("RolandTR909").cpm(60), s("sd").beat("4,12", 16).bank("RolandTR909").cpm(60), s("bd").beat("0,8", 16).bank("RolandTR909").cpm(60) ) ``` The hi-hat plays on every other step (eighth notes), the snare hits on beats 2 and 4, and the bass drum anchors beats 1 and 3. A classic drum pattern — built entirely by clicking on a grid. The beauty here is that you don't need to write any Strudel code yourself. The UI translates your clicks into the exact same pattern objects that Strudel's API understands. --- ## Controls: Tempo, Samples, and Time Signature The step sequencer gives you more than just the grid. A set of controls at the top lets you tweak how the pattern plays. ### Tempo (BPM) A slider controls the tempo: ```javascript updateCpm(newCpm) { this.bpm = newCpm; if (this.isPlaying) { this.play(); } } ``` When you move the slider, the app updates the tempo and restarts the pattern. This value gets passed to Strudel's `.cpm()` function, so the change takes effect immediately. ### Sample Banks You can switch between different drum machine sample banks — everything from the Roland TR-909 to the LinnDrum, the Oberheim DMX, and many more. The app fetches the available banks from the same sample library that Strudel uses: ```javascript async loadBanks() { const ds = "https://raw.githubusercontent.com/felixroos/dough-samples/main/"; const response = await fetch(`${ds}/tidal-drum-machines.json`); const data = await response.json(); // Extract unique bank names from sample keys const banks = new Set(); Object.keys(data).forEach(key => { if (key.includes('_')) { const bankName = key.split('_')[0]; banks.add(bankName); } }); this.availableBanks = Array.from(banks).sort(); } ``` When you select a different bank, every instrument in the sequencer switches to that bank's sounds. Same pattern, completely different character. ### Time Signature You can also switch between 4/4 and 3/4 time: ```javascript updateMeasure(newMeasure) { this.measure = parseInt(newMeasure); this.stepsPerCycle = this.measure * this.stepsPerBeat; this.regenerateInstrumentRows(); if (this.isPlaying) { this.play(); } } ``` In 4/4 time, you get 16 steps. In 3/4 time, you get 12 steps. The grid rebuilds itself, and any active steps that still fit within the new count are preserved. --- ## Adding and Removing Instruments The sequencer starts with four instruments: hi-hat, open hi-hat, snare, and bass drum. But you're not limited to those. A `+` button at the bottom lets you add more instruments from a dropdown: - Ride cymbal - Low Tom - Mid Tom - High Tom - Crash cymbal - Clap Each instrument you add gets its own row in the grid, and it immediately becomes part of the pattern. You can also remove instruments with the `×` button next to each row. Every time you add or remove an instrument, the pattern updates: ```javascript addInstrument(instrument) { if (!this.instruments.includes(instrument)) { this.instruments.push(instrument); this.addInstrumentRow(instrument); if (this.isPlaying) { this.play(); } } } ``` This means you can build up layers in real time — start with just a kick drum, add hi-hats, throw in a clap, experiment with toms. --- ## The Visual Playhead When a pattern is playing, a visual highlight sweeps across the grid to show you which step is currently active. This playhead is driven by a JavaScript timer, separate from Strudel's audio engine: ```javascript startHighlight() { this.startTime = performance.now(); const stepDuration = this.getStepDurationMs(); const tick = () => { const elapsed = performance.now() - this.startTime; const currentStep = Math.floor(elapsed / stepDuration) % this.stepsPerCycle; this.highlight(currentStep); }; tick(); this.highlightInterval = setInterval(tick, Math.min(stepDuration / 2, 50)); } ``` The highlight calculates which step we're on based on elapsed time and the tempo, then applies a `current` CSS class to the corresponding cells. The result is a moving cursor that visually tracks the rhythm — just like the LEDs on a hardware drum machine. --- ## Why This Matters for Creative Coding If you've been following along with this blog, you know that creative coding is about more than just running code — it's about building systems that generate creative output. With visual creative coding, you write rules that produce shapes, colors, and motion. With Strudel, you write rules that produce rhythms, melodies, and textures. This step sequencer sits at the intersection. The grid is the interface. Strudel is the engine. And between them, your clicks become patterns, patterns become code, and code becomes music. What makes this particularly interesting from a creative coding perspective is that the **entire musical composition is described as data**. Each pattern is a set of indices, a sample name, a bank, and a tempo. The `stack()` function layers them together. The system plays the result. This is the same principle behind generative art: describe rules, let the system produce the output. The only difference is that instead of drawing pixels, we're triggering sounds. --- ## Try It Yourself Here are a few things to experiment with: - **Start simple**: Activate just a bass drum on steps 0 and 8\. Add a snare on 4 and 12\. Then layer in hi-hats. Notice how each addition changes the feel. - **Switch banks**: Build a pattern with the Roland TR-909, then switch to the TR-808 or LinnDrum. Same rhythm, completely different vibe. - **Try 3/4 time**: Switch to a 3/4 time signature and notice how 12 steps changes the rhythmic feel. Waltz-like grooves become possible. - **Go weird**: Activate random steps across all instruments. Sometimes the most interesting patterns come from unexpected combinations. - **Think in layers**: Start with the lowest sound (bass drum) and work your way up. This is how a lot of electronic music is built — from the ground up. --- ## How This Connects to Strudel If you've read the [Strudel beginner tutorial](https://alexcodesart.com/making-music-with-code-a-beginners-guide-to-strudel/), you'll notice that the step sequencer uses the exact same Strudel functions we explored there. The difference is that instead of typing this: ```javascript stack( s("bd").beat("0,8", 16).bank("RolandTR909").cpm(60), s("sd").beat("4,12", 16).bank("RolandTR909").cpm(60), s("hh").beat("0,2,4,6,8,10,12,14", 16).bank("RolandTR909").cpm(60) ) ``` ...you click on a grid, and the app builds this for you. This is one of the most powerful ideas in creative coding: **you can build visual interfaces that generate code**. Whether it's a step sequencer that writes Strudel patterns, or a slider panel that adjusts p5.js parameters, the principle is the same. The interface becomes a creative tool that makes the underlying code accessible to anyone — even people who have never written a line of code. --- ## Wrapping Up In this tutorial, we explored how a step sequencer bridges the gap between visual interfaces and code-based music. We looked at: - how the clickable grid stores pattern data - how the app reads the grid and builds Strudel patterns using `s()`, `.beat()`, `.bank()`, `.cpm()`, and `stack()` - how controls for tempo, sample banks, and time signatures shape the output - how adding and removing instruments layers patterns in real time - how a visual playhead tracks the rhythm The step sequencer is a perfect example of what makes creative coding exciting: building systems where simple interactions produce complex, expressive results. If you enjoyed this tutorial, try building your own patterns and see what grooves emerge. And if you want to go deeper into Strudel, check out the [official Strudel documentation](https://strudel.cc/?ref=alexcodesart.com) — there's a whole world of pattern manipulation waiting to be explored. Here is the link to the source code: [GitHub - alexandru-postolache/step-sequencer: A step sequencer to create beats using StrudelA step sequencer to create beats using Strudel. Contribute to alexandru-postolache/step-sequencer development by creating an account on GitHub.![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/icon/pinned-octocat-093da3e6fa40-2.svg)GitHubalexandru-postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/thumbnail/step-sequencer-1)](https://github.com/alexandru-postolache/step-sequencer?ref=alexcodesart.com) Happy coding, and see you in the next tutorial! ### Making Music with Code: A Beginner’s Guide to Strudel URL: https://alexcodesart.com/making-music-with-code-a-beginners-guide-to-strudel/ Last updated: 2026-04-20T20:06:34.000Z Hello friends, and welcome to another creative coding tutorial! Most of the time on this blog we explore **generative art and creative coding with visuals** — using tools like p5.js to draw shapes, animate patterns, or generate abstract compositions. But code isn’t limited to images. It can also generate **sound and music**. In this tutorial, we’re going to explore **Strudel**, a creative coding library that lets you create music directly in the browser using code. By the end of this article you will: - understand the core ideas behind Strudel - create simple drum rhythms with code - generate melodies using patterns - experiment with tempo, silence, and variation Just like generative visuals, the goal here isn’t just to write music — it’s to **design systems that produce music**. Before you start this tutorial, consider signing up to get future articles like this sent straight to your inbox. ## Sign up for Alex Codes Art Art with code for curious minds Subscribe Email sent! Check your inbox to complete your signup. No spam. Unsubscribe anytime. Let’s dive in. --- # What Is Strudel? Strudel is a **browser-based music live coding environment**. You can find the online editor together with documentation at [https://strudel.cc/](https://strudel.cc/?ref=alexcodesart.com) Instead of opening a traditional music production program and arranging notes on a timeline, you describe music using **patterns written in code**. These patterns generate sound events over time. If you’ve explored generative art before, the idea will feel very familiar: Instead of drawing shapes manually, you write **rules that generate shapes**. With Strudel, instead of placing notes manually, you write **rules that generate music**. The result is a very playful workflow: 1. Write a short piece of code 2. Run it 3. Hear the result instantly 4. Modify it and experiment Let’s start with the simplest possible example. # Your First Sound The easiest way to produce sound in Strudel is with the `sound()` function. Here is a minimal example: When you run this, Strudel plays a built-in sound sample called **casio**. Strudel includes a library of sounds and instruments that you can trigger with simple text labels. Try replacing `"casio"` with another sound. For example: Already we can see the philosophy behind Strudel: **simple code that produces immediate feedback**. # Understanding Patterns The most important concept in Strudel is the **pattern**. A pattern describes **how events happen over time**. In music, events could be: - a drum hit - a note - a sample - a sound effect In Strudel, patterns are written as **space-separated sequences**. For example: Let’s break this down. The string inside `sound()` contains four elements, each one triggers a sound. Common drum abbreviations include: - `bd` → bass drum - `sd` → snare drum - `hh` → hi-hat Strudel compresses the entire sequence into something called a **cycle**. A cycle is simply a repeating unit of time. Once the sequence finishes, it loops again. This means a single line of code can generate a repeating rhythm indefinitely. # Changing the Rhythm One of the fun parts about working with patterns is how easy they are to modify. If we add more elements to the sequence, the rhythm becomes denser. More events in the same cycle means the rhythm plays **faster and more complex**. This is one of the core ideas behind algorithmic music: Small textual changes can create **very different musical results**. # Controlling Tempo So far our rhythms are looping automatically, but what if we want to control how fast they play? In Strudel, tempo is measured in **cycles per minute**. We control this with the `setcpm()` function. Example: Here we slow the rhythm down slightly. Because Strudel organizes music around cycles instead of traditional BPM, it becomes very easy to stretch or compress patterns. Think of cycles like the **grid that music sits on**. Everything in the system follows the same timing structure. # Adding Silence Music isn’t just about sound, silence is equally important. In Strudel we can insert pauses using `~`. Example: Here the third step in the pattern is silent. These small gaps create breathing room in the rhythm and make patterns feel more musical. # Nested Rhythms Strudel also allows **nested patterns**. This means we can place smaller patterns inside larger ones. For example: The brackets tell Strudel to play the enclosed elements **faster inside the same step**. So instead of a single hi-hat hit, we get two. This is a very powerful idea because it lets us build **complex rhythmic structures in a very compact way**. # Playing Notes Instead of Samples So far we’ve been triggering drum sounds and samples. But Strudel can also generate **pitched musical notes**, which allows us to create melodies and harmonic patterns. To do this, we use the `note()` function. Here is a simple example: Let’s break down what is happening here. The numbers represent **MIDI note values**. In the MIDI system, every musical note corresponds to a number: - `60` → Middle C - `48` → C in a lower octave - `67` → G So this sequence creates a small melodic pattern. The `.sound()` function tells Strudel **which instrument should play those notes**. In this case, we chose a piano sound. ## Using Note Names Instead of Numbers While MIDI numbers are useful, they can feel a bit abstract if you’re used to thinking about music in terms of **note names**. The good news is that Strudel also lets you write notes using musical notation. For example: Here we’re describing notes the same way musicians usually do, each note contains two pieces of information: - the **note name** (C, D, E, F, G, A, B) - the **octave number -** this is optional For example: - `C4` → middle C - `C5` → the C one octave higher This approach is often easier to read when writing melodies because you can **recognize musical relationships more quickly**. Try modifying the pattern and see what happens. Maybe something like: `C4 D4 E4 G4` or `A3 C4 E4 A4` Small changes like this can produce completely different musical moods. # Layering Instruments Another nice feature of Strudel is that we can layer multiple instruments. Example: Here two instruments play the same notes at the same time. Layering sounds like this is a simple way to create richer textures. # A Small Generative Groove Now that we’ve explored rhythms, tempo, and melodies, let’s combine everything into a **small generative groove**. We’ll create three musical layers: - a **drum rhythm** - a **bass line** - a **simple melody** Each layer is just a pattern, and Strudel plays them together in sync. Let’s break this down. ### 1️⃣ The Drum Pattern `sound("bd ~ sd ~ bd ~ sd ~")` This creates a simple kick and snare rhythm. - `bd` → bass drum - `sd` → snare drum - `~` → a pause The pauses give the rhythm space and make it feel more musical. ### 2️⃣ The Bass Line `note("C2 ~ C2 G1").sound("gm_acoustic_bass")` Here we generate a repeating bass pattern. We use lower notes (`C2`, `G1`) so the bass sits underneath the drums. ### 3️⃣ The Melody `note("C4 E4 G4 B4").sound("gm_lead_6_voice")` This creates a simple melodic sequence using higher notes. Because Strudel loops patterns automatically, the melody keeps repeating and interacting with the bass and drums. ### Why This Works The key function here is `stack()`. `stack()` tells Strudel to **play multiple patterns at the same time**. You can think of it like layering tracks in a music production program: - one track for drums - one for bass - one for melody Except here we’re describing the entire groove **in just a few lines of code**. ### Try Experimenting This is where creative coding becomes fun. Try changing things like: • the drum pattern • the bass notes • the melody • the tempo Even small tweaks can create completely new musical ideas. For example: - change the melody to `C4 D4 E4 G4` - add more hi-hats to the drums - slow the tempo down You might be surprised how quickly new grooves start to emerge. # Why Strudel Is Interesting for Creative Coding If you enjoy **generative art**, Strudel fits naturally into the same mindset. Both systems rely on similar ideas: • patterns • repetition • randomness • small rules producing complex results Just like generative visuals, the most interesting pieces often emerge from **simple systems interacting with each other**. And that’s what makes creative coding so fun. You’re not just composing music. You’re designing **a system that composes music for you**. --- # Wrapping Up Congratulations! 🎉 In this tutorial we explored the basics of **Strudel and musical creative coding**. We looked at: - triggering sounds - building rhythmic patterns - controlling tempo - adding silence - generating melodies If you enjoyed this tutorial, try expanding the examples and building your own generative music sketches. You can combine these ideas with other creative coding tools — imagine pairing **Strudel music with p5.js generative visuals** for a full audiovisual piece. Experiment, tweak the patterns, and see what you can create. You can follow up with the next tutorial here in which we will create a step sequencer using Strudel and Javascript. See you there! [Building a Step Sequencer with Strudel: Creative Coding Meets Visual Beat-MakingHello friends, and welcome to another creative coding tutorial! In the previous tutorial, we explored Strudel — a browser-based creative coding library that lets you make music with code. We wrote drum patterns, melodies, and layered grooves using just a few lines of JavaScript. If you haven’t read that tutorial yet,![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/icon/Logo--1--7.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/thumbnail/Screenshot-2026-04-07-at-10.47.02.png)](https://alexcodesart.com/building-a-step-sequencer-with-strudel-creative-coding-meets-visual-beat-making/) Happy coding, and see you in the next tutorial! 🚀 ### Create Animated Metaballs with Shaders in p5.js — A Creative Coding Tutorial URL: https://alexcodesart.com/create-animated-metaballs-with-shaders-in-p5-js-a-creative-coding-tutorial/ Last updated: 2026-06-26T16:32:09.000Z Hey there and welcome to another tutorial about creative coding and generative art. In this tutorial we will look at what SDFs are and how we can use them to create metaballs. Metaballs are a classic technique in generative art used to create organic, fluid shapes that morph and merge in real time. In this tutorial, you'll learn how to use **GLSL shaders**, **Signed Distance Functions (SDFs)**, and **p5.js** to create a customizable and visually striking metaball animation. We'll build up the shader step by step, exploring techniques for smooth blending, animated motion, lighting, and post-processing effects along the way. Let’s dive in. But first, let's play around with what we are going to create by the end of this tutorial, by tweaking the controls from the right side of the screen (visible on the website only). --- ## What are Shaders & SDFs? **Shaders** are tiny programs that run on the GPU. They come in two flavors: - **Vertex shaders** decide where shapes go on screen. - **Fragment shaders** decide the color of each pixel. In creative coding, fragment shaders are the magic paintbrush. They run once per pixel and let you draw with pure math. **Signed Distance Functions (SDFs)** tell us how far a point is from the surface of a shape: - Negative = inside - Zero = on the edge - Positive = outside This gives us smooth shapes, outlines, and elegant ways to combine things like our blobby metaballs. ## Building the Fragment Shader Step-by-Step ### Shader Basics Before diving deeper, let’s go over a few key concepts that form the backbone of shader programming: - **Main Function:** This is the entry point of every fragment shader. It’s where the actual pixel color is calculated and assigned to `gl_FragColor`. Think of it like the `draw()` function in p5.js, but instead of drawing once per frame, it's executed once per pixel on the screen. Inside `main()`, you typically calculate UV coordinates, apply your shader logic (like field strength or lighting), and output the final color. - **Uniforms** are variables passed into your shader from the outside world (like from your JavaScript sketch). They’re constant across a single draw call. Examples in our shader include `u_resolution`, `u_time`, and `u_numMetaballs`. - **Built-in variables** like `gl_FragCoord` are provided automatically by the GPU. `gl_FragCoord.xy` gives you the pixel coordinates on the screen, which you often normalize using `u_resolution` to get values between 0.0 and 1.0. - **GLSL Data Types**: - `float`: a number with decimals. - `vec2`, `vec3`, `vec4`: vectors with 2, 3, or 4 components (used for positions, colors, etc). - `mat2`, `mat3`, `mat4`: 2x2, 3x3, or 4x4 matrices. Understanding these basics helps you read, write, and play with fragment shaders more fluently. ### Base Shader (Gradient Background) ```glsl #ifdef GL_ES precision mediump float; #endif uniform vec2 u_resolution; void main() { vec2 uv = gl_FragCoord.xy / u_resolution; float t = (uv.x + uv.y) * 0.5; vec3 color = mix(vec3(0.0), vec3(1.0), t); gl_FragColor = vec4(color, 1.0); } ``` **Concept:** This shader is our blank canvas. It converts screen coordinates into UV coordinates (normalized 0-1) and uses them to blend black and white into a simple gradient. It establishes a base on which we can build more complexity. **Code Explanation:** - `uv` is a 2D coordinate between 0 and 1 across the screen. - `t` combines the x and y components into a scalar. - `mix()` linearly blends two colors based on `t`. - The result is a soft black-to-white diagonal gradient. - This setup is foundational and helps us visualize our coordinate space. ![Grayscale diagonal gradient image generated with a basic fragment shader, transitioning from black in the top-left to white in the bottom-right—used as the foundational background in the metaball shader tutorial.](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2025/06/Screenshot-2025-06-29-at-14.51.46.png) Output of the base fragment shader showing a smooth diagonal gradient, our starting point for building the metaball effect. ### One Static Metaball ```glsl #ifdef GL_ES precision mediump float; #endif uniform vec2 u_resolution; void main() { vec2 center = u_resolution * 0.5; float radius = 80.0; float dist = length(gl_FragCoord.xy - center); float field = radius / dist; float fill = smoothstep(1.0, 1.2, field); vec3 color = mix(vec3(0.0), vec3(1.0), fill); gl_FragColor = vec4(color, 1.0); } ``` **Concept:** A metaball is a visual representation of a field. The closer you are to the center, the higher the field strength. We can visualize this as a glowing circle. **Code Explanation:** - We calculate the center of the screen using `u_resolution`. - `radius` defines how large the metaball is. - `length()` gives us the distance from the current pixel to the center of the metaball. - `field = radius / dist` creates a stronger value near the center and weaker further away. - `smoothstep()` softens the edges of the metaball, turning the sharp gradient into a soft glow. - `mix()` blends black and white using the smoothed field as a mask. - Finally, the result is output with full opacity using `vec4(color, 1.0)`. - This is our first true metaball, glowing softly on the screen. ![A white circular blob centered on a black background, created using a static metaball field rendered in a GLSL fragment shader—demonstrating the core concept of field strength and threshold visualization.](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2025/06/Screenshot-2025-06-29-at-14.54.01.png) Visual result of adding a single static metaball using a simple field-based threshold in the fragment shader. ### Multiple Animated Metaballs ```glsl #ifdef GL_ES precision mediump float; #endif uniform vec2 u_resolution; uniform float u_time; uniform int u_numMetaballs; uniform float u_hashSeed; float hash(float n) { return fract(sin(n + u_hashSeed) * 43758.5453); } void main() { vec2 uv = gl_FragCoord.xy; vec2 center = u_resolution * 0.5; float field = 0.0; for (int i = 0; i < 100; i++) { if (i >= u_numMetaballs) break; float fi = float(i); float radius = mix(20.0, 90.0, hash(fi + 300.0)); float freqX = mix(0.8, 1.8, hash(fi + 10.0)); float freqY = mix(0.8, 1.8, hash(fi + 20.0)); float ampX = mix(80.0, 130.0, hash(fi + 30.0)); float ampY = mix(80.0, 130.0, hash(fi + 40.0)); vec2 pos = center + vec2( sin(u_time * freqX + fi) * ampX, cos(u_time * freqY + fi) * ampY ); float dist = length(uv - pos); field += radius / dist; } float fill = smoothstep(1.0, 1.2, field); vec3 color = mix(vec3(0.0), vec3(1.0), fill); gl_FragColor = vec4(color, 1.0); } ``` **Concept:** We generate several metaballs and animate each one along a looping circular trajectory using sine and cosine functions. These individual metaballs interact with each other by contributing to a shared field function. This field accumulates the influence of each ball at every pixel, and when their areas overlap, the field values increase—leading to soft merging effects. This concept of summing fields is at the heart of how metaballs blend organically, rather than appearing as hard-edged circles. **Code Explanation:** - `hash()` is used to generate pseudo-random values deterministically based on the index of the metaball. This keeps each one unique but reproducible. - For each metaball in the loop: - We use `mix()` to interpolate between a minimum and maximum value for each property: `radius`, horizontal and vertical `frequency`, and `amplitude`. These are driven by `hash()` to ensure variation between blobs. - `pos` determines the current position of the metaball using a sine and cosine wave—tied to `u_time`—to create a smooth, circular movement. - `dist` measures how far the current pixel is from the metaball center. - Each metaball contributes `radius / dist` to the total `field`. Since many blobs may affect the same pixel, these field values accumulate, causing regions of stronger influence. - Finally, `smoothstep()` applies a soft threshold around a value of 1.0, blending pixels where the field strength is near that threshold, creating glowing, organic shapes instead of crisp outlines. 0:00 /0:05 1× Animated metaball on a black background, smoothly pulsing and morphing using real-time shader calculations. ### Final Shader: Color, Lighting, and Advanced Effects **New concepts we will introduce to achieve the same esthetics as the one on top of the article:** - **Dynamic Uniforms:** We greatly expand the parameters our shader receives. This includes not just resolution or time, but also a full suite of customizable controls: color gradients for the background, minimum and maximum values for radius, amplitude, and frequency of blob movement, plus visual attributes like outline thickness and color animation amount. These uniforms provide flexibility and fine-tuning for generative expression. - **Color Animation:** The background isn’t static anymore. Instead, it's animated over time using sine and cosine waves for each RGB component. This creates a subtly moving, dreamlike backdrop that enhances the organic feel of the metaballs. - **Accumulative Color:** Each metaball no longer contributes just to the field strength—it also contributes its own unique color, generated using hash functions. These individual contributions are blended into a single color via accumulation and normalization, producing a smooth, multicolored cluster that shifts and evolves with time. - **Lighting Model:** We estimate a gradient of the field by sampling slightly offset pixels. This gives us a vector representing the direction of strongest change—similar to a surface normal. We use this to compute highlights (specular lighting) and shadows, which add visual dimension and depth to the blobs. - **Outline Masking:** The SDF (signed distance function) values from each metaball are smoothly blended using `smoothMin`. We use the resulting minimum distance to generate an outline mask, letting us selectively fade the metaball cluster into the background around the edges. The rest of this tutorial is available ****exclusively for members**. Signing up is ****completely free**, and it helps support more in-depth, beginner-friendly content like this. If you're enjoying the tutorial so far, becoming a member means a lot—it lets me keep sharing creative coding resources without ads or clutter. Plus, once you're in, you'll unlock the full advanced shader code, post-processing effects, and all the juicy details that bring this generative art piece to life. Thanks for being here, and I hope to see you on the other side! _This post is for subscribers only._ ### Drawing Noisy Circles with p5.js: A Deep Dive into Polar Coordinates and Perlin Noise URL: https://alexcodesart.com/drawing-noisy-circles-with-p5-js-a-deep-dive-into-polar-coordinates-and-perlin-noise/ Last updated: 2026-04-07T12:35:09.000Z In this creative coding tutorial, we’re building animated noisy circles using p5.js. These aren’t just ordinary circles—they pulse, shift, and morph over time. The motion comes from Perlin noise, and the structure is based on polar coordinates. You can tweak everything from color modes to noise intensity via a Tweakpane interface. Whether you're just starting to learn to code or diving deeper into generative art, this sketch offers a hands-on way to explore math, motion, and design. --- ## The Setup Function Let’s break down the `setup()` function: ```javascript function setup() { createCanvas(window.innerWidth, window.innerHeight, WEBGL); pixelDensity(4); setupGui(); } ``` We use `WEBGL` to allow for more advanced transformations and better performance. `pixelDensity(4)` sharpens visuals, especially on high-resolution displays. Finally, `setupGui()` initializes our interactive controls using Tweakpane. ## The Draw Function Every frame, the canvas refreshes with a new frame of shifting curves: ```javascript function draw() { apply2DTransformations(); noFill(); strokeWeight(params.weight); colorGen = new ColorGenerator(params.baseColor); complementary = colorGen.getShades(2); background(complementary[1]); switch (params.colorMode) { case "tints": colors = colorGen.getTints(params.numberOfCurves, 90); break; case "shades": colors = colorGen.getShades(params.numberOfCurves, 10); break; case "triadic": colors = colorGen.getTriadic(); break; case "tetradic": colors = colorGen.getTetradic(); break; } createNoisyCircles(width / 2, height / 2, colors); } ``` We: - Set stroke weight and disable fill - Generate a background color based on shades of the base color - Pick a color palette based on the selected color mode - Call `createNoisyCircles()` to draw all the animated curves To easily generate colors that work together, I used p5.colorGenerator, a library I created that can be found here: [GitHub - alexandru-postolache/p5.colorGenerator: A library for p5.js to create color palettes.A library for p5.js to create color palettes. Contribute to alexandru-postolache/p5.colorGenerator development by creating an account on GitHub.![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/icon/pinned-octocat-093da3e6fa40.svg)GitHubalexandru-postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/thumbnail/p5.colorGenerator)](https://github.com/alexandru-postolache/p5.colorGenerator?ref=alexcodesart.com) ## Creating Noisy Circles Here’s the core of the visual effect: ```javascript function createNoisyCircles(centerX, centerY, colors) { for (j = 0; j < params.numberOfCurves; j++) { beginShape(); stroke(colors[j % colors.length]); curveNoiseFactor = params.noiseFactor + j; for (i = 0; i <= params.resolution; i++) { circlePoint = map(i, 0, params.resolution, 0, TWO_PI); curveRadius = j * params.gap; x = centerX + cos(circlePoint) * curveRadius; y = centerY + sin(circlePoint) * curveRadius; n = noise( x * params.noiseDetail, y * params.noiseDetail, frameCount * params.speed ); let offsetX = n * cos(circlePoint) * curveNoiseFactor; let offsetY = n * sin(circlePoint) * curveNoiseFactor; vertex(x + offsetX, y + offsetY); } endShape(); } } ``` ### Shape Drawing: beginShape(), vertex(), endShape() This trio of functions is how p5.js draws custom shapes. - `beginShape()` tells p5.js you're about to define a shape. - `vertex(x, y)` places a point. - `endShape()` finishes the shape and connects all the points. In our case, each loop over `i` adds a new vertex to form a circle-like path. Because of the noise, it's not a perfect circle—it looks more organic, like ripples or ink on wet paper. ### The Role of map() ```javascript circlePoint = map(i, 0, params.resolution, 0, TWO_PI); ``` The `map()` function remaps values from one range to another. Here, we’re taking a loop variable `i` from `0` to `params.resolution`, and translating that into angles from `0` to `TWO_PI` (which is 360° in radians). This turns each value of `i` into a point along the circle’s circumference. ### Polar Coordinates in Action ```javascript x = centerX + cos(circlePoint) * curveRadius; y = centerY + sin(circlePoint) * curveRadius; ``` Using cosine and sine with the angle lets us calculate the x and y coordinates of a point on a circle. Multiply those by the radius, and you've got a full circle around the center. I explained more about polar coordiantes in this article, if you want to learn more [Create Abstract Art with p5.js: Animate the Sun and WavesHello and welcome back to another exciting tutorial! Today, we’ll dive deeper into creative coding with p5.js and explore some fundamental programming concepts. In this session, we’ll create an abstract art piece featuring a sun and waves, and by the end, we’ll animate both the sun and the waves![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/icon/Logo--1--1.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/thumbnail/download--17-.png)](https://alexcodesart.com/create-abstract-art-with-p5-js-animate-the-sun-and-waves/) ### Introducing Perlin Noise ```javascript n = noise(x * params.noiseDetail, y * params.noiseDetail, frameCount * params.speed); ``` Perlin noise gives us smooth randomness. By feeding it x, y, and time (`frameCount * speed`), we get a shifting value between 0 and 1 that changes slowly and predictably over time. This noise value is used to create displacement: ```javascript let offsetX = n * cos(circlePoint) * curveNoiseFactor; let offsetY = n * sin(circlePoint) * curveNoiseFactor; ``` We offset each vertex outward or inward based on the noise value, creating the effect of a circle that breathes or morphs as time passes. ### Looping Over Multiple Curves We draw multiple noisy circles by repeating the process `params.numberOfCurves` times. Each circle gets its own radius and slightly different noise factor, which increases outward: ```javascript curveNoiseFactor = params.noiseFactor + j; ``` The result is a series of layered, animated, organic shapes that shimmer and move independently. ## Interactive Controls with Tweakpane Users can tweak noise strength, resolution, curve count, spacing, color modes, and stroke thickness: ```javascript pane.addInput(params, "noiseDetail", { min: 0, max: 0.3, step: 0.001 }); pane.addInput(params, "numberOfCurves", { min: 1, max: 150, step: 1 }); pane.addInput(params, "colorMode", { options: { Tints: "tints", Shades: "shades", Triadic: "triadic", Tetradic: "tetradic" }, }); ``` This makes the sketch not just a generative system but a playground for experimentation. ## Final Thoughts This sketch is a fun way to explore how math and noise can work together to produce flowing, organic animations. Generative art is all about systems and surprises—and here, both come to life through circles that are never quite the same. I encourage you to play around with the sliders and see what you can come up with. Here are a few of my results: ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2025/06/download--1-.png) ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2025/06/download--2-.png) ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2025/06/download--3-.png) Different results by playing around with the sliders 🥳 That's all, congrats for following along and learning more about creative coding, generative art, Perlin noise and p5.js. Like always, you can find the full code here: [Lesson 10 by alex.codes.art -p5.js Web EditorA web editor for p5.js, a JavaScript library with the goal of making coding accessible to artists, designers, educators, and beginners.![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/icon/favicon-2.ico)](https://editor.p5js.org/alex.codes.art/sketches/mukYcMTM8?ref=alexcodesart.com) --- To stay informed about future articles, feel free to subscribe. It’s free, and your support means a lot. Thank you! ## Sign up for Alex Codes Art Art with code for curious minds Subscribe Email sent! Check your inbox to complete your signup. No spam. Unsubscribe anytime. --- ## Wrapping Up Thank you for following along with this tutorial! If you have any questions, feedback, or just want to share your own creations, please feel free to leave a comment below. I’ll make sure to respond and help you out as best as I can. Stay connected for more exciting tutorials and creative coding tips by subscribing to this blog. I really appreciate it! Happy coding, and see you in the next tutorial! ## Next tutorial In the next tutorial, we will explore the world of shaders and how we can use them to create metaballs, using a concept called SDFs. I hope to see you there! [Create Animated Metaballs with Shaders in p5.js — A Creative Coding TutorialHey there and welcome to another tutorial about creative coding and generative art. In this tutorial we will look at what SDFs are and how we can use them to create metaballs. Metaballs are a classic technique in generative art used to create organic, fluid shapes that morph and merge![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/icon/Logo--1--4.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/thumbnail/download--2--1-1.png)](https://alexcodesart.com/create-animated-metaballs-with-shaders-in-p5-js-a-creative-coding-tutorial/) ### Building an Interactive Generative Art with p5.js, Tweakpane, and Watercolor Effects URL: https://alexcodesart.com/building-an-interactive-generative-art-with-p5-js-tweakpane-and-watercolor-effects/ Last updated: 2026-04-07T12:35:34.000Z In the previous tutorial, we looked at how we can build an interactive piece of digital art using p5.js and we talked a bit about the math behind it. [Mastering Creative Coding: Building Interactive Radial Strokes with p5.jsHello friends, and welcome to another creative coding tutorial! Today, we’re going to create an interactive piece of digital art using p5.js. You can interact with this artwork by changing parameters in the top right corner, and watch as the digital art transforms in real-time. Getting Started with JavaScript![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/icon/Logo--1-.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/thumbnail/radial-strokes--9-.png)](https://alexcodesart.com/mastering-creative-coding-building-interactive-radial-strokes-with-p5-js/) This tutorial walks through creating a customizable generative art grid using p5.js, [Tweakpane](https://tweakpane.github.io/docs/?ref=alexcodesart.com), and the [p5.brush](https://github.com/freshfork/p5.brush?ref=alexcodesart.com) library for watercolor textures. Whether you're new to creative coding or looking to expand your generative art toolkit, this project blends structure, randomness, and interactivity to produce unique visual compositions. We’ll also look at how this sketch became the foundation for an interactive artwork generator available at [canvas.alexcodesart.com](https://canvas.alexcodesart.com/?ref=alexcodesart.com), where answering a few simple questions creates a one-of-a-kind digital artwork. --- ## What We're Building This project creates a grid of rectangles that can be styled with watercolor fills, hatching, and strokes. All visual aspects are tweakable through a user interface. It’s a perfect introduction to: - Generative art techniques - Creative coding with p5.js - Using Tweakpane for live parameter editing - Building with classes in JavaScript - Integrating p5.brush for painterly effects It’s beginner-friendly and great for anyone learning to code through art. ## Setting Up the Canvas We start by creating a WEBGL canvas with high pixel density for crisp visuals: ```javascript function setup() { createCanvas(600, 600, WEBGL); pixelDensity(3); setupTweakpane(); } ``` WEBGL is used to support advanced drawing and p5.brush functionality. The brush setup allows us to achieve textures that mimic ink and watercolor. ## Interactive Parameters with Tweakpane Tweakpane provides a clean UI to adjust parameters like grid size, padding, margins, fill strategy, and visual styles like stroke and hatch. Here's a snippet showing how we allow the user to choose color variation style: ```javascript pane.addInput(params, "colorVariation", { options: { Tint: COLOR_VARIATION_TINT, Shade: COLOR_VARIATION_SHADE, }, }); ``` Other customizable parameters include number of rows and columns, padding, margin, fill strategies (random, row, column), and visual enhancements like stroke weight and hatch angle. ```javascript pane.addInput(params, "rows", { min: 1, max: 30, step: 1 }); pane.addInput(params, "cols", { min: 1, max: 30, step: 1 }); pane.addInput(params, "strokeStyleColor", { view: "color" }); ``` Every change triggers a redraw by setting `parametersChanged = true`, ensuring instant visual feedback. ## The Grid Class: Structure Meets Style The `Grid` class is the heart of the sketch. It handles layout, color assignment, sizing logic, and rendering. Here's how it works: ### Grid Initialization ```javascript constructor(width, height, rows, cols) { this.width = width; this.height = height; this.rows = rows; this.cols = cols; this.#occupied = Array(rows).fill().map(() => Array(cols).fill(false)); } ``` We use an internal `#occupied` array to manage which grid cells are already taken when shapes span multiple cells. ### Setting Fill Color ```javascript getColorFill(i, j) { if (this.colorFillStrategy === Grid.COLOR_FILL_ROW) { return this.colors[j % this.colors.length]; } else if (this.colorFillStrategy === Grid.COLOR_FILL_COLUMN) { return this.colors[i % this.colors.length]; } else { return this.colors[int(random(0, this.colors.length))]; } } ``` This lets us decide how color gets applied—across rows, columns, or randomly. ### Size Variation ```javascript getSizeFactor(i, j) { let maxW = 1; let maxH = 1; while (j + maxW < this.cols && !this.#occupied[i][j + maxW] && maxW < this.itemMaxWidthFactor) maxW++; while (i + maxH < this.rows && !this.#occupied[i + maxH][j] && maxH < this.itemMaxHeightFactor) maxH++; return [floor(random(1, maxW + 1)), floor(random(1, maxH + 1))]; } ``` This gives visual variety by allowing some shapes to span multiple grid cells. ## Adding Texture with p5.brush Using the `p5.brush` library, we simulate watercolor fills and pencil-like hatching: ```javascript setupFillAndStroke(fillColor) { if (this.colorFillStyle === Grid.COLOR_FILL_STYLE_WATERCOLOR) { brush.fill(fillColor, 75); brush.bleed(0.03, "out"); brush.fillTexture(0.6, 0.4); brush.stroke(this.strokeStyle.color); brush.strokeWeight(this.strokeStyle.weight); } else { fill(fillColor); stroke(this.strokeStyle.color); strokeWeight(this.strokeStyle.weight); } } ``` We also add hatch lines for texture: ```javascript if (this.hatchStyle.enabled) { brush.hatch(this.hatchStyle.distance, this.hatchStyle.angle); brush.setHatch('hatch_brush', this.hatchStyle.color, this.hatchStyle.weight); } ``` This creates a rich visual texture that sets this apart from flat, digital visuals. ## Drawing the Grid The main `draw()` function brings everything together. Here's a simplified view: ```javascript function draw() { if (!parametersChanged) return; parametersChanged = false; background(240); apply2DTransformations(); let colorGen = new ColorGenerator(params.startColor); let colors = params.colorVariation === COLOR_VARIATION_TINT ? colorGen.getTints(params.cols) : colorGen.getShades(params.cols); grid = new Grid(width, height, params.rows, params.cols); grid.setColors(colors); grid.setColorFillStrategy(params.colorFillStrategy); grid.setColorFillStyle(params.colorFillStyle); grid.draw(); } ``` Each rectangle is rendered according to all the styles and logic you configure via the UI. --- ## From Sketch to Artwork Generator Inspired by this sketch, I built an interactive generative art experience: [Create Your Unique Artwork | Alex Codes ArtGenerate personalized digital artwork based on your personality and preferences.![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/icon/favicon.png)Alex Codes Art![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/thumbnail/logo-horizontal.png)](https://canvas.alexcodesart.com/?ref=alexcodesart.com) Instead of tweaking sliders, users answer a few simple questions. Their answers feed into the code to generate a completely unique piece of generative art—no two are the same. This bridges code art with personalization, creating a fun and accessible entry point into creative coding. ## Why This Is Great for Beginners - No advanced math or graphics knowledge required - Real-time feedback helps you learn by doing - Teaches essential JavaScript and p5.js concepts - Easily expandable: add animation, export, or save features Whether you're just learning to code or looking to experiment with generative visuals, this is a practical, rewarding project. --- ## Final Thoughts Creative coding is one of the most exciting ways to learn programming. With tools like p5.js and libraries like p5.brush, you can create expressive, organic visuals with just a few lines of code. As always, the full code can be found here: [Lesson 9 by alex.codes.art -p5.js Web EditorA web editor for p5.js, a JavaScript library with the goal of making coding accessible to artists, designers, educators, and beginners.![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/icon/favicon-1.ico)](https://editor.p5js.org/alex.codes.art/sketches/XamQhJmLp?ref=alexcodesart.com) This generative art grid is a great starting point. Play with the code, tweak the UI, change the layout—see what you can come up with. Then, take it further. Make it yours. Happy coding! --- Want to stay updated with new articles? Just hit subscribe — it’s completely free, and I’d really appreciate the support. Thanks a lot! ## Sign up for Alex Codes Art Art with code for curious minds Subscribe Email sent! Check your inbox to complete your signup. No spam. Unsubscribe anytime. --- ## Next tutorial If you enjoyed building the generative art grid, the next step is to explore shape and motion using noise and polar coordinates. In the follow-up tutorial, we’ll create dynamic, rippling circles that animate in real-time using Perlin noise. You’ll learn how to use trigonometry, `map()`, and vertex-based drawing to build flowing, organic visuals — all fully customizable with Tweakpane. [Drawing Noisy Circles with p5.js: A Deep Dive into Polar Coordinates and Perlin NoiseIn this creative coding tutorial, we’re building animated noisy circles using p5.js. These aren’t just ordinary circles—they pulse, shift, and morph over time. The motion comes from Perlin noise, and the structure is based on polar coordinates. You can tweak everything from color modes to noise![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/icon/Logo--1--2.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/thumbnail/download.png)](https://alexcodesart.com/drawing-noisy-circles-with-p5-js-a-deep-dive-into-polar-coordinates-and-perlin-noise/) ### Mastering Creative Coding: Building Interactive Radial Strokes with p5.js URL: https://alexcodesart.com/mastering-creative-coding-building-interactive-radial-strokes-with-p5-js/ Last updated: 2026-04-07T12:35:20.000Z Hello friends, and welcome to another creative coding tutorial! Today, we're going to create an interactive piece of digital art using p5.js. You can interact with this artwork by changing parameters in the top right corner, and watch as the digital art transforms in real-time. ## Getting Started with JavaScript Classes In this tutorial, we’ll use a JavaScript class to describe and draw arcs. If you're not familiar with classes in JavaScript, don't worry! I’ve got you covered with a detailed introduction in this article: [Understanding JavaScript Classes for Creative CodingWhen diving into creative coding, one of the most powerful tools at your disposal is JavaScript classes. If you’ve been tinkering with code for a while, you’ve probably heard of object-oriented programming (OOP). Classes are at the heart of OOP, and they can help you organize and structure your code![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/size/w256h256/2024/06/Logo--1-.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/size/w1200/2024/08/grid0.jpg)](https://alexcodesart.com/understanding-javascript-classes-for-creative-coding/) In short, classes are a fundamental part of object-oriented programming (OOP) and help you organize your code by bundling properties and methods into reusable blueprints for objects. ## Analyzing the Structure of an Arc Before we dive into the code, let's break down the properties that define an arc in our artwork. Each arc represents a portion of a circle, so it can be described using: - **x, y coordinates**: The center point of the arc. - **Radius**: The distance from the center to any point on the arc. - **Start and End Angles**: These determine the section of the circle that the arc covers. - **Color**: The hue of the arc. - **Weight**: The thickness of the arc’s stroke. ### Defining the RadialStroke Class To encapsulate these properties, we can define a `RadialStroke` class in JavaScript: ```javascript class RadialStroke { constructor(x, y, distance, angleStart, angleFinish, color, weight) { this.x = x; this.y = y; this.distance = distance; this.angleStart = angleStart; this.angleFinish = angleFinish; this.color = color; this.weight = weight; } draw() { stroke(this.color); strokeWeight(this.weight); if (this.angleStart > this.angleFinish) { let newStart = this.angleFinish; this.angleFinish = this.angleStart; this.angleStart = newStart; } beginShape(); for (let i = this.angleStart; i <= this.angleFinish; i++) { let a = map(i, 0, 360, 0, TWO_PI); let newX = this.x + cos(a) * this.distance; let newY = this.y + sin(a) * this.distance; vertex(newX, newY); } endShape(); } } ``` ### Understanding the Draw Method In the `draw()` method, we define how the arc will be drawn: 1. **Setting the Stroke**: We start by setting the stroke color and weight. 2. **Angle Adjustment**: If the start angle is greater than the end angle, we swap them to ensure the arc is drawn correctly. 3. **Defining Vertices**: Using a loop, we calculate the position of each vertex on the arc. The `map()` function converts degrees into radians, which are then used in the cosine and sine functions to determine the `x` and `y` coordinates of each point on the arc. If you're new to polar coordinates, you might find my article helpful: [Create Abstract Art with p5.js: Animate the Sun and WavesHello and welcome back to another exciting tutorial! Today, we’ll dive deeper into creative coding with p5.js and explore some fundamental programming concepts. In this session, we’ll create an abstract art piece featuring a sun and waves, and by the end, we’ll animate both the sun and the waves![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/size/w256h256/2024/06/Logo--1-.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/07/download--17-.png)](https://alexcodesart.com/create-abstract-art-with-p5-js-animate-the-sun-and-waves/) ## Implementing the Radial Strokes Now that we have our `RadialStroke` class, let's use it to create our dynamic artwork. We’ll start by defining some variables and settings: ```javascript let settings = { arcs: 30, radius: { min: 1, max: 360 }, gap: { min: 15, max: 25 }, weight: { min: 2, max: 15 }, arcsColor: "#dbf7ff", gradient: "tints", background: "#012d3a", speed: { min: 0, max: 0.003 }, directions: "both", }; let curves = []; ``` ## Setting Up the Canvas Next, let's define the `setup()` function: ```javascript function setup() { createCanvas(window.innerWidth, window.innerHeight); pixelDensity(4); createRadialStrokes(); } ``` Here’s what happens: - **Canvas Creation**: We create a canvas that spans the full width and height of the window. - **Pixel Density**: We increase the pixel density for sharper visuals. - **Calling createRadialStrokes()**: This function will initialize the arcs based on the settings. The GUI, which allows you to tweak various parameters of the artwork in real-time, is created using Tweakpane. However, I won’t dive into the details of how Tweakpane works in this article. ## Creating the Radial Strokes The `createRadialStrokes()` function generates each arc using the `RadialStroke` class: ```javascript function createRadialStrokes() { colorGen = new ColorGenerator(settings.arcsColor); let colors; if (settings.gradient == "tints") { colors = colorGen.getTints(settings.arcs); } else { colors = colorGen.getShades(settings.arcs); } gap = random(settings.gap.min, settings.gap.max); for (let i = 0; i < settings.arcs; i++) { let angleStart = int(random(settings.radius.min, settings.radius.max)); let angleFinish = int(random(settings.radius.min, settings.radius.max)); let movementDirection; switch (settings.directions) { case "both": movementDirection = int(random(0, 2)); break; case "left": movementDirection = 1; break; case "right": movementDirection = 0; break; } let movementSpeed = random(settings.speed.min, settings.speed.max); let curveWeight = random(settings.weight.min, settings.weight.max); curves[i] = new RadialStroke( width / 2, height / 2, i * gap, angleStart, angleFinish, colors[i], curveWeight ); } } ``` In this function: - **Color Selection**: We generate tints or shades based on user settings. I do this using another class I created, which is available in the source code given at the end of the article - **Gap Calculation**: The distance between arcs is randomized for a more dynamic look. - **Arc Creation**: For each arc, we randomly determine the start and end angles, the direction, and the movement speed, then create an instance of `RadialStroke`. ## **Bringing It All Together: The draw() Function** Finally, let’s look at the draw() function, which ties everything together by rendering the radial strokes on the canvas: ```javascript function draw() { background(settings.background); noFill(); for (i = 0; i < settings.arcs; i++) { curves[i].draw(); } } ``` In this function: • **Clearing the Canvas**: We start by setting the background color, which resets the canvas at the beginning of each frame. • **No Fill for Shapes**: We ensure that our arcs are only stroked and not filled with color. • **Rendering the Arcs**: The loop iterates over each arc, drawing it based on the properties defined in the RadialStroke class. This `draw()` function is what makes your artwork dynamic, as it continuously refreshes the display with the latest settings and positions of the arcs, giving the impression of movement and interaction. --- Don’t miss any new posts — subscribe for free! It really helps me out, and I’d love to have you along. Thanks! ## Sign up for Alex Codes Art Art with code for curious minds Subscribe Email sent! Check your inbox to complete your signup. No spam. Unsubscribe anytime. --- ## Conclusion By following this tutorial, you've learned how to use JavaScript classes in p5.js to create interactive, dynamic radial strokes. This process not only deepens your understanding of object-oriented programming but also opens up new possibilities for creative coding. You can find the full code for this project here [Lesson 8 by alex.codes.art -p5.js Web EditorA web editor for p5.js, a JavaScript library with the goal of making coding accessible to artists, designers, educators, and beginners.![](https://editor.p5js.org/favicon.ico)](https://editor.p5js.org/alex.codes.art/sketches/M9-vYRoZm?ref=alexcodesart.com) Feel free to experiment with the settings to create unique patterns and share your creations with the community. Don’t forget to check out my other tutorials to continue your journey into creative coding and generative art! Happy coding! --- ## Next Tutorial In the next article, we will look at how we can create a generative art, using a nice watercolor effect and a dynamic grid. See you there! [Building an Interactive Generative Art with p5.js, Tweakpane, and Watercolor EffectsIn the previous tutorial, we looked at how we can build an interactive piece of digital art using p5.js and we talked a bit about the math behind it. Mastering Creative Coding: Building Interactive Radial Strokes with p5.jsHello friends, and welcome to another creative coding tutorial! Today, we’![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/icon/Logo--1--3.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/thumbnail/artwork--6-.png)](https://alexcodesart.com/building-an-interactive-generative-art-with-p5-js-tweakpane-and-watercolor-effects/) ### Understanding JavaScript Classes for Creative Coding URL: https://alexcodesart.com/understanding-javascript-classes-for-creative-coding/ Last updated: 2025-07-01T14:26:34.000Z When diving into creative coding, one of the most powerful tools at your disposal is JavaScript classes. If you've been tinkering with code for a while, you've probably heard of object-oriented programming (OOP). Classes are at the heart of OOP, and they can help you organize and structure your code in a way that makes it more reusable, readable, and scalable—perfect for those generative art projects! In this article, we'll break down what JavaScript classes are, why they’re useful for creative coding, and how you can start using them in your projects today. Whether you're a beginner or looking to refine your skills, understanding classes will elevate your coding game. ## What Are JavaScript Classes? At its core, a class is like a blueprint for creating objects. In JavaScript, objects are collections of related data and functionality. Think of a class as a template—you define the structure and behavior of the objects that can be created from it. This is especially useful in creative coding when you want to manage complex elements like shapes, animations, or interactive components in your generative art. Here's a simple example of a JavaScript class: ```javascript class Circle { constructor(x, y, radius) { this.x = x; this.y = y; this.radius = radius; } draw() { ellipse(this.x, this.y, this.radius * 2); } move(dx, dy) { this.x += dx; this.y += dy; } } ``` In this `Circle` class, we’ve defined a blueprint for creating circle objects. Each circle has properties like `x`, `y`, and `radius`, and methods like `draw` and `move`. You can create multiple instances of `Circle`, each with its own position and size, but all sharing the same behavior. ## Why Use Classes in Creative Coding? Using classes can streamline your creative coding process in several ways: - **Reusability**: Once you've created a class, you can reuse it across different projects. For instance, if you've made a class for handling particles in a particle system, you can easily integrate it into other projects without rewriting the code. - **Organization**: Classes help keep your code organized, especially in larger projects. You can bundle related functions and data together, making it easier to manage and modify your code. - **Scalability**: As your projects grow in complexity, classes allow you to scale your codebase efficiently. By encapsulating functionality within classes, you can add new features or tweak existing ones without breaking your entire project. ## How to Create and Use a JavaScript Class Let's take a deeper dive into creating and using JavaScript classes in your creative coding projects. ## Defining a Class A class in JavaScript is defined using the `class` keyword followed by the class name. Inside the class, you define a constructor method and any other methods that your objects will need. ```javascript class Particle { constructor(x, y, speed, direction) { this.x = x; this.y = y; this.speed = speed; this.direction = direction; } update() { this.x += cos(this.direction) * this.speed; this.y += sin(this.direction) * this.speed; } display() { ellipse(this.x, this.y, 5, 5); } } ``` Here, the `Particle` class has a constructor that initializes the particle's position, speed, and direction. The `update` method moves the particle, and the `display` method draws it on the screen. ## Creating Objects (Instances) from a Class Once you've defined a class, you can create objects from it—these objects are called instances. Here’s how you would create a few particles: ```javascript let particles = []; for (let i = 0; i < 100; i++) { particles.push(new Particle(random(width), random(height), random(1, 3), random(TWO_PI))); } ``` This code snippet creates an array of `Particle` instances with random positions, speeds, and directions. ## Using Methods To make your particles come to life, you’ll need to update and display them in your `draw` loop: ```javascript function draw() { background(0); for (let particle of particles) { particle.update(); particle.display(); } } ``` Each particle’s `update` method is called to move it, and `display` is called to draw it. Notice how clean and organized the code remains, even as the complexity increases. ## Extending Classes In creative coding, you might find that some shapes or behaviors are similar but not identical. JavaScript classes support inheritance, allowing you to create new classes based on existing ones. For example, you might have a basic `Shape` class and then extend it to create more specific shapes like `Rectangle` and `Triangle`: ```javascript class Shape { constructor(x, y) { this.x = x; this.y = y; } move(dx, dy) { this.x += dx; this.y += dy; } } class Rectangle extends Shape { constructor(x, y, width, height) { super(x, y); this.width = width; this.height = height; } draw() { rect(this.x, this.y, this.width, this.height); } } ``` The `Rectangle` class extends the `Shape` class, inheriting its properties and methods, while also adding a `draw` method specific to rectangles. This approach makes your code more modular and easier to manage. ## Practical Applications in Creative Coding Now that you understand the basics of classes, let’s look at how they can be applied in real-world creative coding projects. ### 1\. Particle Systems Classes are perfect for managing complex systems like particles. You can create a `Particle` class and then use it to generate hundreds or thousands of particles, each behaving according to the rules you define in the class. ### 2\. Interactive Art If you're building interactive art pieces, classes can help you manage user interactions. For example, you could create a `Button` class to handle different buttons on your canvas, each responding to clicks or other events in a consistent way. ### 3\. Procedural Generation For those into generative art, classes can help you create more sophisticated and reusable code. For instance, you might create a `Tree` class to generate procedural trees, with each instance representing a unique tree. --- Want to stay updated with new articles? Just hit subscribe — it’s completely free, and I’d really appreciate the support. Thanks a lot! ## Sign up for Alex Codes Art Art with code for curious minds Subscribe Email sent! Check your inbox to complete your signup. No spam. Unsubscribe anytime. --- ## Conclusion Understanding and utilizing JavaScript classes can take your creative coding to the next level. By organizing your code into classes, you’ll make it more efficient, readable, and scalable, allowing you to focus on the creative aspects of your work. Whether you're building particle systems, interactive art, or generative landscapes, JavaScript classes provide the structure and flexibility you need. So, dive in, experiment, and see how classes can transform your coding projects! And remember, the more you practice, the more intuitive classes will become. Happy coding! In this article, we've covered the fundamentals of JavaScript classes and their practical applications in creative coding. Be sure to explore other articles on our blog for more tips, tutorials, and insights into the world of generative art and creative coding with JavaScript. ### Learn Creative Coding: Build Geometric Abstract Art with p5.js URL: https://alexcodesart.com/learn-creative-coding-build-geometric-abstract-art-with-p5-js/ Last updated: 2025-07-01T14:25:18.000Z **Hello friends, and welcome to a new creative coding tutorial!** In this tutorial, we’re going to create a geometric abstract art piece using **JavaScript** and **p5.js**. This project is perfect for beginners in creative coding who are interested in exploring **generative art** techniques. ## **What We’re Going to Create** Take a look at the abstract art piece we’ll be making. This is an interactive piece so feel free to play around with the settings: ## **Breaking Down the Design** Let’s break down the steps to create this piece of abstract art with code: - We’ll be working with rectangles that are aligned vertically. - The rectangles are aligned either to the left or right, following the top rectangle’s position. - The corners of the rectangles have varying radii depending on their alignment. - The rectangles also vary in width, adding to the dynamic nature of the composition. ## **Setting Up Variables** To begin, we need to define several variables such as the number of items, spacing between them, border radius, and the minimum and maximum width of the rectangles. We’ll store these variables in a `settings` object: ```javascript let settings = { numberOfItems: 10, padding: 2, cornerRadius: 50, minWidth: 180, minWidthMax: 400, maxWidth: 260, maxWidthMax: 600, } let colors = ["#031d44","#04395e","#70a288","#dab785","#d5896f"]; ``` ## **Setting Up the Canvas** Next, let’s start with our `setup` function: ```javascript function setup() { createCanvas(400, 600); pixelDensity(3); rectMode(CORNERS); noStroke(); } ``` We’re using `rectMode(CORNERS)` to make it easier to align the rectangles based on the corners' x-y coordinates. This mode interprets the first two parameters of the `rect()` function as the top-left corner and the last two as the bottom-right corner. ## **Drawing the Rectangles** In the `draw` function, we’ll calculate the height of each rectangle and set a random width within the defined minimum and maximum range. We’ll also define default values for left and right alignment, which we’ll use for positioning the first item. ```javascript function draw() { background(240); let itemWidth = random(settings.minWidth, settings.maxWidth); let itemHeight = (height - ((settings.numberOfItems - 1) * settings.padding)) / settings.numberOfItems; let leftAlign = (width / 2) - (itemWidth / 2); let rightAlign = (width / 2) + (itemWidth / 2); drawRectangles(itemWidth, itemHeight, leftAlign, rightAlign); } ``` ## **Creating the `drawRectangles` Function** We’ve already called our `drawRectangles` function, so let’s create it next. Here’s what this function needs to do: - Iterate over the number of items we defined. - Translate vertically to the position of the current item. - Define the fill color for each rectangle. - Draw rectangles aligned to the left or right based on their index, with border radius applied to the correct corners. - Update the left or right alignment for the next rectangle. ```javascript function drawRectangles(itemWidth, itemHeight, leftAlign, rightAlign) { for (i = 0; i < settings.numberOfItems; i++) { push(); translate(0, (itemHeight + settings.padding) * i); fill(colors[i % colors.length]); if (i % 2 == 0) { rect(leftAlign, 0, leftAlign + itemWidth, itemHeight, 0, settings.cornerRadius, 0, settings.cornerRadius); rightAlign = leftAlign + itemWidth; } else { rect(rightAlign - itemWidth, 0, rightAlign, itemHeight, settings.cornerRadius, 0, settings.cornerRadius, 0); leftAlign = rightAlign - itemWidth; } itemWidth = random(settings.minWidth, settings.maxWidth); pop(); } } ``` ## **Wrapping Up** 🥳 **That’s it! Congratulations** on creating your own piece of generative abstract art with **p5.js**! This tutorial has guided you through some fundamental concepts of creative coding, and now you have a solid foundation to build upon. If you enjoyed this tutorial and want to dive deeper into creative coding, be sure to check out our other tutorials on **p5.js** and **JavaScript**. You can find the full code for this project [Lesson 7 by alex.codes.art -p5.js Web EditorA web editor for p5.js, a JavaScript library with the goal of making coding accessible to artists, designers, educators, and beginners.![](https://editor.p5js.org/favicon.ico)](https://editor.p5js.org/alex.codes.art/sketches/r2uUBZkXr?ref=alexcodesart.com) --- ## **Stay Connected** Thank you for following along with this creative coding journey! If you have any questions, feedback, or want to share your own generative art creations, feel free to leave a comment below. I’m always here to help and would love to see what you’ve made. Don’t forget to subscribe to this blog for more exciting tutorials and creative coding tips. Happy coding, and see you in the next tutorial! ## Sign up for Alex Codes Art Art with code for curious minds Subscribe Email sent! Check your inbox to complete your signup. No spam. Unsubscribe anytime. --- ## Next Tutorial In the next tutorial, we will create an interactive abstract art using p5.js. We will explore what classes are in JavaScript and how we can use them to better organise the code. See you there! [Mastering Creative Coding: Building Interactive Radial Strokes with p5.jsHello friends, and welcome to another creative coding tutorial! Today, we’re going to create an interactive piece of digital art using p5.js. You can interact with this artwork by changing parameters in the top right corner, and watch as the digital art transforms in real-time. Getting Started with JavaScript![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/size/w256h256/2024/06/Logo--1-.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/size/w1200/2024/09/radial-strokes--9-.png)](https://alexcodesart.com/mastering-creative-coding-building-interactive-radial-strokes-with-p5-js/) ### Animating Abstract Art: A Beginner’s Guide to Tweening with p5.js URL: https://alexcodesart.com/animating-abstract-art-a-beginners-guide-to-tweening-with-p5-js/ Last updated: 2025-07-01T14:23:46.000Z Hello friends! Today, we are diving into the world of **creative coding** by making a beautiful piece of abstract art and animating it using **tweening** in **p5.js**. This tutorial is perfect for **coding beginners** interested in **generative art**. First, let’s take a look at the final piece and identify its elements. 0:00 /0:05 1× We have two groups of semicircles, ranging from largest to smallest, each with different tints. These semicircles are translated left or right and drawn progressively smaller. ## **Step 1: Define Variables** Let’s start by defining a few variables we’ll use later. ```javascript let options = { nrOfCircles: 10, endDegreeTop: 0, endDegreeBottom: 0, delay: 0, }; const startSize = 400; const backgroundStartSize = 1500; const lowerHalfColors = [ '#2E84EE', '#4290F0', '#569BF1', '#6AA7F3', '#7EB3F5', '#93C0F6', '#A8CCF8', '#BDD8FA', '#D3E5FC', '#E9F2FD' ]; const upperHalfColors = [ '#EE982E', '#F0A242', '#F1AC56', '#F3B66A', '#F5C07E', '#F6CA93', '#F8D4A8', '#FADEBD', '#FCE9D3', '#FDF4E9' ]; ``` These variables are self-explanatory. We’ll use options.delay later to animate the semicircles. ## **Step 2: Setup Function** Our setup function initializes the canvas and sets some initial values. ```javascript function setup() { createCanvas(600, 600); options.endDegreeTop = TWO_PI; options.endDegreeBottom = PI; } ``` We create a 600x600 canvas and set `endDegreeTop` to `TWO_PI` and `endDegreeBottom` to `PI`. We can’t do this when defining the `options` object because `TWO_PI` and `PI` are constants provided by **p5.js**. ## **Step 3: Drawing Semicircles** Next, we’ll create a function to draw the semicircles. ```javascript function drawSemicircles(nrOfCircles, colors, alpha, startSize, sizeDifference, startDegree, endDegree, direction) { for (let i = 0; i < nrOfCircles; i++) { push(); let fillColor = color(colors[i]); fillColor.setAlpha(alpha); fill(fillColor); if (direction) { translate(width / 2 + (i * sizeDifference) * 0.5, height / 2); } else { translate(width / 2 - (i * sizeDifference) * 0.5, height / 2); } arc(0, 0, startSize - (i * sizeDifference), startSize - (i * sizeDifference), startDegree, endDegree); pop(); } } ``` In this function, we iterate over the number of circles, set the fill color with transparency, and translate the semicircles to the left or right before drawing them. The `fill` and `translate` calls are wrapped with `push()` and `pop()` to restrain their effects to that context. ## **Step 4: Draw Function** Now, let’s look at the draw function. ```javascript function draw() { background(240); noStroke(); const sizeDifference = startSize / options.nrOfCircles; drawSemicircles(options.nrOfCircles, upperHalfColors, 255, startSize, sizeDifference, PI, options.endDegreeTop, false); drawSemicircles(options.nrOfCircles, lowerHalfColors, 255, startSize, sizeDifference, 0, options.endDegreeBottom, true); } ``` First, we calculate the size difference between semicircles. Then, we call our `drawSemicircles` function twice: once for the upper semicircles and once for the lower ones. ## **Step 5: Animating with p5.tween** Finally, let’s animate this using the [**p5.tween** library](https://github.com/Milchreis/p5.tween?ref=alexcodesart.com). A “tween” generates intermediate frames between keyframes to create the illusion of motion or transformation. ```javascript p5.tween.manager.addTween(options, 'tween') .addMotions([ { key: 'endDegreeTop', target: TWO_PI }, { key: 'endDegreeBottom', target: PI }, ], 1000, 'easeInCubic') .addMotion('nrOfCircles', 10, 1200, 'easeOutCubic') .addMotion('delay', 0, 500, 'easeOutCubic') .addMotion('nrOfCircles', 1, 1000, 'easeInCubic') .addMotions([ { key: 'endDegreeTop', target: PI }, { key: 'endDegreeBottom', target: 0 }, ], 1000, 'easeOutCubic') .startTween(); ``` We use three methods from this library. `addTween` creates a new tween with the options object. `addMotions` specifies the properties to change, their targets, durations, and easing functions. The motions in `addMotions` execute simultaneously, while those in `addMotion` execute sequentially. The `delay` key is used to pause for 500 milliseconds before animating other properties. Here are a few examples based on different values used for the number inside the `translate` function. I encourage you to play around with that number, which initially was `0.5` ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/07/download--24-.png) ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/07/download--23-.png) ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/07/download--25-.png) Very different results by changing only one number 🥳 That's all, congrats for following along and learning more about creative coding and p5.js. Like always, you can find the full code here: [Lesson 6 by alex.codes.art -p5.js Web EditorA web editor for p5.js, a JavaScript library with the goal of making coding accessible to artists, designers, educators, and beginners.![](https://editor.p5js.org/favicon.ico)](https://editor.p5js.org/alex.codes.art/sketches/Ic6PXIVkg?ref=alexcodesart.com) --- ## Wrapping Up Thank you for following along with this tutorial! If you have any questions, feedback, or just want to share your own creations, please feel free to leave a comment below. I’ll make sure to respond and help you out as best as I can. Stay connected for more exciting tutorials and creative coding tips by subscribing to this blog. I really appreciate it! Happy coding, and see you in the next tutorial! --- Don’t miss any new posts — subscribe for free! It really helps me out, and I’d love to have you along. Thanks! ## Sign up for Alex Codes Art Art with code for curious minds Subscribe Email sent! Check your inbox to complete your signup. No spam. Unsubscribe anytime. --- ## Next tutorial In the next tutorial, we will explore how to create a piece of geometric abstract art using p5.js and consolidate the knowledge of `push()`, `pop()` and `translate()` functions together with other programming concepts. See you there! [Learn Creative Coding: Build Geometric Abstract Art with p5.jsHello friends, and welcome to a new creative coding tutorial! In this tutorial, we’re going to create a geometric abstract art piece using JavaScript and p5.js. This project is perfect for beginners in creative coding who are interested in exploring generative art techniques. What We’re Going to![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/size/w256h256/2024/06/Logo--1-.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/08/download--1--2.png)](https://alexcodesart.com/learn-creative-coding-build-geometric-abstract-art-with-p5-js/) ### Create Abstract Art with p5.js: Animate the Sun and Waves URL: https://alexcodesart.com/create-abstract-art-with-p5-js-animate-the-sun-and-waves/ Last updated: 2025-07-01T14:22:56.000Z Hello and welcome back to another exciting tutorial! Today, we'll dive deeper into creative coding with p5.js and explore some fundamental programming concepts. In this session, we'll create an abstract art piece featuring a sun and waves, and by the end, we'll animate both the sun and the waves to bring our artwork to life. ### Identifying the Components Let's start by identifying the components of our digital art. We'll have: 1. A sun, represented by a circle with surrounding triangles rotated at different angles. 2. Three waves, each with different colors and curves. Unlike [the previous tutorial ](https://alexcodesart.com/creating-stylized-waves-with-p5-js-a-creative-coding-tutorial/)where we used noise to create waves, we'll use the sinusoidal (sin) function to draw more regular, repeating curves. ### Setting Up the Canvas Our `setup` function will create a canvas for our artwork: ```javascript function setup() { createCanvas(400, 600); } ``` ### Drawing the Sun First, we'll define a function to draw the sun. This function will take the x and y coordinates of the center and the radius as inputs. We'll disable the stroke and draw a circle filled with an orange color. Then, we'll use another function, `drawSunRays`, to draw the surrounding triangles. ```javascript function drawSun(centerX, centerY, radius) { noStroke(); fill("#b4481a"); circle(centerX, centerY, 220); let numberOfTriangles = 10; let distance = 140; let triangleSize = 20; drawSunRays(centerX, centerY, numberOfTriangles, distance, triangleSize); } ``` ### Drawing the Sun Rays We will explore a very powerful and elegant concept called **polar coordinates.** By default, p5.js uses the [Cartesian coordinates (x,y)](https://en.wikipedia.org/wiki/Cartesian%5Fcoordinate%5Fsystem?ref=alexcodesart.com) to describe the position of a point in a 2d plane**.** In p5.js, the origin point is the top-left corner of the canvas which is described by the (0,0) coordinates and any other point (x,y) is described by the distance from the origin point on the x and y axis (horizontal and vertical axis). Another two-dimensional coordinate system is **polar coordinates**. Instead of using the signed distances along the two coordinate axes, polar coordinates specify the location of a point 𝑃 in the plane by its distance 𝑟 from the origin and the angle 𝜃 made between the line segment from the origin to 𝑃 and the positive 𝑥 axis. The polar coordinates (r,θ) of a point P are illustrated in the below figure. ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/07/Untitled_Artwork.png) Point P is represented in polar coordinates, using the distance r and the angle θ I will not dive deeper into the math of this but I encourage you to [read more about it here](https://mathinsight.org/polar%5Fcoordinates?ref=alexcodesart.com). What we need to know is the formula to convert from cartesian to polar coordinates and those are `x = r * cos(angle), y = r * sin(angle)` where `r` is the radius and `angle` is the angle with the x-axis. The angle range is between `0` and `2 * PI`. This represents 360 degrees. So let’s give it a try. We'll start by drawing circles at these positions to verify our calculations: ```javascript function drawSunRays(centerX, centerY, numberOfTriangles, distance, triangleSize) { for (let i = 0; i < numberOfTriangles; i++) { let angle = map(i, 0, numberOfTriangles, 0, TWO_PI); let x = centerX + cos(angle) * distance; let y = centerY + sin(angle) * distance; circle(x, y, 10); } } ``` We will iterate over every triangle we want to create and then we will map the number `i` between `0` and `TWO_PI` since that represents a full loop. Then, we apply the formulas to convert from cartesian to polar coordinates and draw circles instead of triangles, to test that what we have is correct. What we have now is this. ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/07/download--18--1.png) Math magic! Great work so far! ### Replacing Circles with Triangles The next step is to make those triangles instead of circles. The challenge comes from them having different rotations and for that, we will use the translate(), push(), and pop() functions from p5.js. ```javascript function drawSunRays(centerX, centerY, numberOfTriangles, distance, triangleSize) { for (let i = 0; i < numberOfTriangles; i++) { let angle = map(i, 0, numberOfTriangles, 0, TWO_PI); let x = centerX + cos(angle) * distance; let y = centerY + sin(angle) * distance; push(); translate(x, y); rotate(angle + HALF_PI); triangle(-triangleSize, triangleSize, triangleSize, triangleSize, 0, -triangleSize); pop(); } } ``` The official explanation of the push and pop function is > Begins a drawing group that contains its own styles and transformations. > > By default, styles such as [fill()](https://p5js.org/reference/p5/fill?ref=alexcodesart.com) and transformations such as [rotate()](https://p5js.org/reference/p5/rotate?ref=alexcodesart.com) are applied to all drawing that follows. The [push()](https://p5js.org/reference/p5/push?ref=alexcodesart.com) and [pop()](https://p5js.org/reference/p5/pop?ref=alexcodesart.com) functions can limit the effect of styles and transformations to a specific group of shapes, images, and text. So, to limit the effect of `translate()` and `rotate()` to only one triangle, we wrap that code with `push()` and `pop()`. Then, we want to rotate the triangle but the rotate function rotates the objects around the origin point and you remember that the origin point of the canvas in p5js is the top-left corner and that is not useful since we want to rotate the triangle around his own center. To do this, we call `translate(x,y)` which moves the origin point at those coordinates. Then calling the rotate function with the angle we calculated previously on which we add `HALF_PI` will give us exactly the result we want. Then, the `triangle()` function accepts 6 parameters, which represent the x and y coordinates of the 3 points of the triangle. Because we just moved the origin point to (x,y) by calling the translate(x,y), the call to the triangle function will use that as the origin when drawing it so the coordinates we pass are relative to the new origin point. Then, when we are done with drawing one triangle, we call `pop()` and this will remove the effects of translate and rotate so we can start again. To better visualize how the triangle is getting drawn using those coordinates, here is a diagram, showing it for a triangle with size 4. ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/07/Untitled_Artwork-2.png) A triangle with the center in (0,0) and with all edges of length 4. This is what we get now: ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/07/download--19--1.png) ### Drawing the Waves Next, let's draw the waves. We'll create a generic function `drawWave` that takes the color, height, period, and amplitude as parameters. This function will draw lines from the left to the right of the canvas, with their height controlled by the sin function. We can control the look of the wave by altering the xScale and yScale parameters. ```javascript function drawWave(color, waveHeight, xScale, yScale) { stroke(color); for (let i = 0; i < width; i++) { let y = yScale * sin(i * xScale) + waveHeight; line(i, height, i, height - y); } } ``` ### Putting It All Together In the `draw` function, we'll call the previously defined functions to draw the sun and waves: ```javascript function draw() { background("#e1d7bb"); drawSun(width / 2, height / 3.3, 220); drawWave("#28636f", 200, 0.02, 30); drawWave("#1c4457", 130, 0.016, 12); drawWave("#0d1d38", 70, 0.02, 25); } ``` You can see we called the `drawWave` function 3 times, with different parameters, to get different looks. ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/07/download--17--1.png) ### Extra: Animating the Sun and Waves To animate the sun and waves, we'll use the sin function with slightly increasing inputs every frame. We'll define two new variables and update our functions accordingly. ```javascript let wavesStartOffset = {}; let sunRaysOffset = 0; ``` For the sun rays, we'll add a `rotationSpeed` parameter and update the `drawSunRays` function: ```javascript function drawSunRays(centerX, centerY, numberOfTriangles, distance, triangleSize, rotationSpeed) { for (let i = 0; i < numberOfTriangles; i++) { let angle = map(i, 0, numberOfTriangles, 0, TWO_PI); let x = centerX + cos(angle + sunRaysOffset) * distance; let y = centerY + sin(angle + sunRaysOffset) * distance; push(); translate(x, y); rotate(angle + HALF_PI + sunRaysOffset); triangle(-triangleSize, triangleSize, triangleSize, triangleSize, 0, -triangleSize); pop(); } sunRaysOffset += rotationSpeed; } ``` For the waves, we'll use an object to control the speed of each wave: ```javascript function drawWave(color, waveHeight, xScale, yScale, offsetSpeed) { if (!(color in wavesStartOffset)) { wavesStartOffset[color] = 0; } stroke(color); for (let i = 0; i < width; i++) { let y = yScale * sin(i * xScale + wavesStartOffset[color]) + waveHeight; line(i, height, i, height - y); } wavesStartOffset[color] += offsetSpeed; } ``` 0:00 /0:02 1× And there you have it! You've successfully created and animated an abstract art piece with p5.js. Congrats! Keep experimenting with different parameters to create unique effects. A few ways to make this art yours and learn along the way would be: - change the sun radius and position - adjust the number of triangles, the size and distance - draw 10 waves instead of 3 and see how that looks Like always, you can find the full code here: [Lesson 5 by alex.codes.art -p5.js Web EditorA web editor for p5.js, a JavaScript library with the goal of making coding accessible to artists, designers, educators, and beginners.![](https://editor.p5js.org/favicon.ico)](https://editor.p5js.org/alex.codes.art/sketches/%5FOswikuzF?ref=alexcodesart.com) --- ## Wrapping Up Thank you for following along with this tutorial! If you have any questions, feedback, or just want to share your own creations, please feel free to leave a comment below. I’ll make sure to respond and help you out as best as I can. Stay connected for more exciting tutorials and creative coding tips by subscribing to this blog. I really appreciate it! Happy coding, and see you in the next tutorial! --- To stay informed about future articles, feel free to subscribe. It’s free, and your support means a lot. Thank you! ## Sign up for Alex Codes Art Art with code for curious minds Subscribe Email sent! Check your inbox to complete your signup. No spam. Unsubscribe anytime. --- ## Next tutorial In the next tutorial we will explore how to animate an abstract art using tweening in p5.js. See you there! [Animating Abstract Art: A Beginner’s Guide to Tweening with p5.jsHello friends! Today, we are diving into the world of creative coding by making a beautiful piece of abstract art and animating it using tweening in p5.js. This tutorial is perfect for coding beginners interested in generative art. First, let’s take a look at the final piece and![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/size/w256h256/2024/06/Logo--1-.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/07/0000143-1.png)](https://alexcodesart.com/animating-abstract-art-a-beginners-guide-to-tweening-with-p5-js/) ### Create Stunning Generative Art with Circles in p5.js URL: https://alexcodesart.com/create-stunning-generative-art-with-circles-in-p5-js/ Last updated: 2025-07-01T14:22:11.000Z Welcome back to another exciting tutorial about creative coding and generative art! Today, we'll dive into creating a simple composition with concentric circles and some text. In the second part of this tutorial, we'll use p5.gui.js to create a small graphical interface, allowing us to easily manipulate parameters and experiment by tweaking some values. Let's get started! ## Drawing the Circles We'll begin by defining a few variables inside an object that we'll later use to draw the circles. ```javascript let props = { circleNo: 5, sizeDifference: 75, baseCircleSize: 50, colorDifference: 12, baseColor: '#e76f51', backgroundColor: '#2a9d8f', }; ``` Next, we'll set up our canvas in the `setup` function: ```javascript function setup() { createCanvas(400, 500); } ``` In the `draw` function, we'll first set the background color and then draw the concentric circles. We need to draw the circles from the largest to the smallest to ensure each new shape covers the previous one appropriately. ```javascript function draw() { background(props.backgroundColor); colorMode(HSB, 360, 100, 100); for (let i = props.circleNo - 1; i >= 0; i--) { let colorObj = color(props.baseColor); let h = hue(colorObj); let s = saturation(colorObj); let b = brightness(colorObj); fill(color((h + (props.colorDifference * i)) % 360, s, b)); circle(width / 2, height / 2, (props.baseCircleSize + (i * props.sizeDifference))); } } ``` We first set the background color and then switch the color mode to HSB for easier color manipulation. The `for` loop iterates in decreasing order to draw the largest circles first. We adjust the hue value for each circle using the modulo operator to keep it within the 0-359 range. Play around with saturation and brightness to see different results! This is what we got so far: ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/07/download--10-.png) ## Understanding Color Modes Now, let’s talk a bit about color modes. The default color mode in p5.js is RGB. This stands for Red, Green, Blue, and every color is made of 3 values, from 0-255, where each value represents the amount of red, green, and blue the color has. For example, `(255, 0, 0)` is pure red, and `(0, 255, 0)` is pure green. Using this color mode while trying to obtain other colors close to the one you’re using can be challenging. That’s why we will use the HSB color mode. This stands for Hue, Saturation, and Brightness, where each value is made of 3 components. In this color mode, each color is made of 3 values, but this time in a range from 0-100 by default. - **Hue** represents the type of color we see. It’s the aspect of color described by names like red, blue, yellow, and green. - **Saturation** measures the intensity or purity of the color. A saturation of 100 means the color is fully intense, while 0 means it’s a shade of gray. - **Brightness** indicates how light or dark the color is. At 100, the color is as bright as possible; at 0, it is completely black. In p5.js, you can also specify different ranges for each component, and we will use this to set the hue component between 0-360, so we have more control over the color changes. ## Enhancing with a GUI Library Now, let's add some interactivity by using the p5.gui library. This will allow real-time adjustments to the properties of our circles, making our artwork dynamic and customizable. **Setting Up p5.gui** You first need to download the quicksettings.js and p5.gui.js files from here [p5.gui/libraries at master · bitcraftlab/p5.guip5.gui magically generates a graphical user interface for your p5.js sketches - bitcraftlab/p5.gui![](https://github.githubassets.com/assets/pinned-octocat-093da3e6fa40.svg)GitHubbitcraftlab![](https://opengraph.githubassets.com/0011a3aaa9124bd115443292065c939034ed3331a5c3a183adeeabbc97740e2d/bitcraftlab/p5.gui)](https://github.com/bitcraftlab/p5.gui/tree/master/libraries?ref=alexcodesart.com) First, include the p5.gui library in your project by adding this scripts to your HTML file: ```html ``` Define our properties object with additional parameters for the p5.gui library. You can use the same property name and append `Min`, `Max` and `Step` to customise the minimum, maximum and the step for the sliders. ```javascript var props = { // Circle properties circleNo: 5, circleNoMin: 1, circleNoMax: 30, circleNoStep: 1, // main circle size baseCircleSize: 50, baseCircleSizeMin: 10, baseCircleSizeMax: 200, baseCircleSizeStep: 1, // Size difference sizeDifference: 75, sizeDifferenceMin: 1, sizeDifferenceMax: 100, sizeDifferenceStep: 1, // Color difference colorDifference: 12, colorDifferenceMin: 1, colorDifferenceMax: 50, colorDifferenceStep: 1, // Stroke weight strokeWeightValue: 1, strokeWeightValueMin: 0, strokeWeightValueMax: 10, strokeWeightValueStep: 1, // Stroke setting hasStroke: false, // Colors strokeColor: '#ffffff', baseColor: '#e76f51', backgroundColor: '#2a9d8f', }; function setup() { createCanvas(400, 500); var gui = createGui("Settings"); gui.addObject(props); } ``` In the `setup` function, we call the `createGui` function and pass the settings object. The library will generate a user interface with sliders and checkboxes based on our properties. Let's enhance the `draw` function to include stroke settings. You can add this code right after setting the background color. ```javascript if (!props.hasStroke) { noStroke(); } else { stroke(props.strokeColor); strokeWeight(props.strokeWeightValue); } ``` This is the result: ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/07/Screenshot-2024-07-05-at-11.34.23.png) Now, go and play around with all the settings there. You will see you can create something quite unique just by tweaking some parameters. This is the beauty of art made with code! 0:00 /0:33 1× ## Adding Text to the Canvas Let’s enhance our artwork by adding an inspirational message. First, we need to download a font and include it in our p5.js sketch. The `preload` function gets called once, before `setup` and `draw`. I used this font which [you can find here](https://fonts.google.com/specimen/Luckiest+Guy?ref=alexcodesart.com). Once you download it, add it on the same folder with your sketch.js file. ```javascript let font; function preload() { font = loadFont('LuckiestGuy-Regular.ttf'); } ``` We will create a function called `addText` which we will call from our `draw` function. ```javascript function addText() { textFont(font); textAlign(CENTER); textSize(50); stroke(255); strokeWeight(3); fill(props.baseColor); text("Stay focused!", width / 2, height / 1.15); } ``` This function sets the font, alignment, size, and color of the text before displaying it at the specified position on the canvas. The `text` function writes "Stay focused!" centered horizontally and slightly above the bottom of the canvas. We will also need to adjust the height of the circles by changing the second parameter for the `circle` function to `height / 2.5`. So now we will have our final result ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/07/download--11-.png) --- ## Next Steps If we want to change anything about the styling or the text value, we would need to change the code. But what if we make those parameters, like the font size, position, text value as settings that we can modify using the GUI we created. So this is what you can play and experiment with next. Play around with all the settings we have on the GUI and post them here! I'm super curious what you created with it. Here are a few of mine. ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/07/download--12-.png) ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/07/download--13-.png) ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/07/download--14-.png) ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/07/download--15-.png) Like always, you can find the full code here: [p5.js Web EditorA web editor for p5.js, a JavaScript library with the goal of making coding accessible to artists, designers, educators, and beginners.![](https://editor.p5js.org/favicon.ico)](https://editor.p5js.org/alex.codes.art/sketches/d3ukjHKGj?ref=alexcodesart.com) --- ## Wrapping Up Thank you for following along with this tutorial! If you have any questions, feedback, or just want to share your own creations, please feel free to leave a comment below. I’ll make sure to respond and help you out as best as I can. Stay connected for more exciting tutorials and creative coding tips by subscribing to this blog. I really appreciate it! Happy coding, and see you in the next tutorial! --- To stay informed about future articles, feel free to subscribe. It’s free, and your support means a lot. Thank you! ## Sign up for Alex Codes Art Art with code for curious minds Subscribe Email sent! Check your inbox to complete your signup. No spam. Unsubscribe anytime. --- ### Next Tutorial In the next tutorial, we’ll dive into creating a beautiful abstract art with sun and waves. We will be learning about **polar coordinates**, `translate(), rotate(), push() and pull()` p5.js functions and exploring more programming concepts. See you there! [Create Abstract Art with p5.js: Animate the Sun and WavesHello and welcome back to another exciting tutorial! Today, we’ll dive deeper into creative coding with p5.js and explore some fundamental programming concepts. In this session, we’ll create an abstract art piece featuring a sun and waves, and by the end, we’ll animate both the sun and the waves![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/size/w256h256/2024/06/Logo--1-.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/07/download--17-.png)](https://alexcodesart.com/create-abstract-art-with-p5-js-animate-the-sun-and-waves/) ### Creating Stylized Waves with p5.js: A Creative Coding Tutorial URL: https://alexcodesart.com/creating-stylized-waves-with-p5-js-a-creative-coding-tutorial/ Last updated: 2025-07-01T14:21:16.000Z Hello and welcome to another exciting creative coding tutorial! Today, we will dive into the world of stylized waves using p5.js. This tutorial is perfect for beginners and seasoned coders alike. We’ll be exploring two powerful features of p5.js: `noise` and `random`. Thanks to these, every time you run your code, your artwork will be unique, yet maintain the same artistic style. This is where the magic of generative art truly shines. ### Breaking Down the Process To get started, let's break our project down into simpler steps. Before we create diagonal, curvy lines, we'll start with straight lines of different colors, spaced evenly apart. #### Step 1: Defining Colors First, we'll define a color palette for our waves: ```javascript const colors = [ "#ecd2b0", "#efcea5", "#e7b987", "#e0ab84", "#e7eceb", "#72adc5", "#3783af", "#06649c", "#0258a3", "#0452a8" ]; ``` #### Step 2: Setting Up the Canvas Next, we’ll set up our canvas. The setup function runs once and prepares the canvas for drawing: ```javascript function setup() { createCanvas(400, 500); noLoop(); } ``` #### Step 3: Drawing Straight Lines Now, let's work on our `draw` function. We’ll start by defining the space between the lines. We want equal spacing between them so for that we can just divide the total `width` of the canvas to the number of lines we have. We will use the colors variable length since we will draw one line with one color. So our `spaceBetween` variable can be defined like this: `let spaceBetween = width / (colors.length - 1);` Let’s get started with drawing our lines. We’ll draw them from the right side of the canvas to the left, ensuring that each new wave overlaps the previous one. We’ll iterate from the last color in our palette to the first, creating horizontal lines from left to right for each wave. Here’s how the code looks: ```javascript function draw() { background(colors[colors.length - 1]); let spaceBetween = width / (colors.length - 1); let curveWidth; for (let i = colors.length - 1; i >= 0; i--) { stroke(colors[i]); curveWidth = i * spaceBetween; for (let j = 0; j < height; j++) { let y = j; line(0, y, curveWidth, y); } } } ``` In our code, we use two nested for loops. The outer loop iterates over the colors, determining the number of waves to draw. The inner loop is responsible for drawing each wave by calling the line function. It draws horizontal lines from left to right, moving down one step at a time. As a result, our canvas will look like this: ![Straight Lines](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/06/download--4-.png) This is quite nice already :) . Good job! To better visualize what’s happening under the hood, let’s add a small delay between each line being drawn so we see the process. ![Curvy Waves](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/06/Untitled.gif) Drawing process ### Adding Curviness with Noise Now, let’s look at how we can add some “curviness” to those lines, to make them look more like waves. To do this, we will use the [mighty noise function](https://processing.org/reference/noise%5F.html?ref=alexcodesart.com). Noise is a very powerful tool used in a lot of places. For short, what it does, is it returns semi-random values for given inputs. The trick with this is that for very close inputs it returns very close outputs as well, making things look more organic and more realistic. We will see it at work now. #### Step 4: Drawing Curvy Waves We’ll start by isolating the wave-drawing logic into a new function called `drawWaveWithNoise(curveWidth)`. Here, we want the values on the x-axis to change, based on the noise, so we will get a curvy line instead of a straight one. First, we need to prepare the input for the noise function. We want our input to be quite small, so the changes given by the noise function are also small. For that, we need to define two more variables, a `noiseLevel` and a `noiseScale`. Let’s use some arbitrary values for now of 50 and 0.01. We want our noise input to slightly change every time we pass it to the noise function so our `noiseInput` will be `noiseScale * j` ```javascript function drawWaveWithNoise(curveWidth) { let noiseLevel = 50; let noiseScale = 0.01; // iterate over every pixel, from the top to the bottom and draw lines for (let j = 0; j < height; j++) { let y = j; let noiseInput = noiseScale * j; let x = noiseLevel * noise(noiseInput); line(x, y, x + curveWidth, y); } } ``` Running this function gives us a more interesting visual effect: ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/06/Screenshot-2024-06-27-at-14.47.49.png) Lines with noise become curvy lines Nice! Progress but not there yet. ### Enhancing Uniqueness with Random You see that all waves do not follow the same curve. That’s because for our `noiseInput` we use the same value every time. To improve this, we can randomly choose a value between a range, so that each wave is different. Also, by calling the [noiseSeed() ](https://p5js.org/reference/?ref=alexcodesart.com#/p5/noiseSeed)after every wave, with different values, we make sure they will be more unique. ```javascript function drawWaveWithNoise(curveWidth) { let noiseLevel = random(70, 110); let noiseScale = random(0.004, 0.008); noiseSeed(random(0, 1000)); for (let j = 0; j < height; j++) { let y = j; let noiseInput = noiseScale * j; let x = noiseLevel * noise(noiseInput); line(x, y, x + curveWidth, y); } } ``` This will produce even more diverse and interesting wave patterns: ![Unique Waves](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/06/Screenshot-2024-06-27-at-14.54.30.png) More unique waves ### Creating Diagonal Waves Cool! We also want them to be diagonal so for this we need to subtract bigger and bigger values from the x variable: ```javascript function drawWaveWithNoise(curveWidth) { let noiseLevel = random(70, 110); let noiseScale = random(0.004, 0.008); noiseSeed(random(0, 1000)); for (let j = 0; j < height; j++) { let y = j; let noiseInput = noiseScale * j; let x = (noiseLevel * noise(noiseInput)) - (j * 0.5); line(x, y, x + curveWidth, y); } } ``` ![Diagonal Waves](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/06/Screenshot-2024-06-27-at-14.57.33.png) ### Something Extra: Adding Importance to Colors Now, let’s make it extra nice. If you look at this, you see that every color has an equal spacing between them. In other words, every color is taking up the same amount of space in the canvas ( if we don’t take into consideration the differences between different noises that each wave is having). But what if we want that decide that one color should take more space than others? Maybe we want more sand in the image or different distributions between them. We can make this happen. First, we need to assign an “importance” for each color which will represent how much space one color should take in relation to the others. So let’s change our color array in an object with these properties ```javascript const colors = [ { "color": "#ecd2b0", "importance": 4 }, { "color": "#efcea5", "importance": 1 }, { "color": "#e7b987", "importance": 3 }, { "color": "#e0ab84", "importance": 2 }, { "color": "#e7eceb", "importance": 2 }, { "color": "#72adc5", "importance": 2 }, { "color": "#3783af", "importance": 2 }, { "color": "#06649c", "importance": 2 }, { "color": "#0258a3", "importance": 2 }, { "color": "#0452a8", "importance": 2 } ]; ``` Then, we have to find out what one importance point means related to the width of the canvas, so how many pixels of the width one importance point is taking. ```javascript // calculate importance point to width importanceTotal = 0; importanceArr = []; for (let i = colors.length - 1; i >=0; i--) { importanceTotal += colors[i].importance; importanceArr[i] = colors[i].importance; } importancePointToPixel = width / importanceTotal; ``` We are also creating an importance array with all the values that we will use next. Because we draw the canvas from the right to the left, we need to be able to know how much space each wave will need. To do this, we will use a technique called a [prefix sum](https://en.wikipedia.org/wiki/Prefix%5Fsum?ref=alexcodesart.com). A prefix sum of an array is another array where each element is the sum of all the previous elements, including the current one. You can read more about it on the Wikipedia page. We will define this function as such: ```javascript function fillPrefixSum(arr) { let prefixSum = []; prefixSum[0] = arr[0]; for (let i = 1; i < arr.length; ++i) { prefixSum[i] = prefixSum[i - 1] + arr[i]; } return prefixSum; } ``` Now, in our `draw()` function, we will call this function and pass the result to the `drawWaveWithNoise` function ```javascript ... importancePointToPixel = width / importanceTotal; prefixSum = fillPrefixSum(importanceArr); for (let i = colors.length - 1; i >= 0; i--) { stroke(colors[i].color); await drawWaveWithNoise(prefixSum[i] * importancePointToPixel); } ``` Let’s look at a few results where I changed the importance parameters. ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/06/Screenshot-2024-06-28-at-08.49.13-1.png) ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/06/Screenshot-2024-06-28-at-08.50.15.png) ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/06/Screenshot-2024-06-28-at-08.53.19.png) ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/06/Screenshot-2024-06-28-at-08.53.56.png) Now, different colors take up a different amount of space in the canvas ### Animating the Waves We can animate this in a simple way, the same way we did in the previous tutorial, by calling a sleep function after each wave is drew. ![Animated Waves](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/06/Screen-Recording-2024-06-28-at-08.57.53.gif) Waves being drew with a delay ### Experiment and Explore You can make this art your own by: - Changing the color palette - Adjusting the number of colors (and waves) - Tinkering with the importance of each color - Tweaking the noise values Like always, the full code can be found here [p5.js Web EditorA web editor for p5.js, a JavaScript library with the goal of making coding accessible to artists, designers, educators, and beginners.![](https://editor.p5js.org/favicon.ico)](https://editor.p5js.org/alex.codes.art/sketches/a9zITA07Q?ref=alexcodesart.com) --- ### Wrapping Up Thank you for following along with this tutorial! If you have any questions, feedback, or just want to share your own creations, please feel free to leave a comment below. I’ll make sure to respond and help you out as best as I can. Stay connected for more exciting tutorials and creative coding tips by subscribing to this blog. I really appreciate it! Happy coding, and see you in the next tutorial! --- Want to stay updated with new articles? Just hit subscribe — it’s completely free, and I’d really appreciate the support. Thanks a lot! ## Sign up for Alex Codes Art Art with code for curious minds Subscribe Email sent! Check your inbox to complete your signup. No spam. Unsubscribe anytime. --- ### Next Tutorial In the next tutorial, we’ll dive into creating a more complex piece of art using additional p5.js functions and exploring more programming concepts. See you there! [Create Stunning Generative Art with Circles in p5.jsWelcome back to another exciting tutorial about creative coding and generative art! Today, we’ll dive into creating a simple composition with concentric circles and some text. In the second part of this tutorial, we’ll use p5.gui.js to create a small graphical interface, allowing us to easily manipulate parameters![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/size/w256h256/2024/06/Logo--1-.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/07/download--11--1.png)](https://alexcodesart.com/create-stunning-generative-art-with-circles-in-p5-js/) ### Vibrant Digital Art: Creating a Bauhaus-Inspired Grid of Colorful Shapes with Code URL: https://alexcodesart.com/creating-bauhaus-inspired-grid/ Last updated: 2025-07-01T14:20:20.000Z ## In this tutorial, I'll guide you through the process of creating a Bauhaus-inspired grid of colorful shapes using code. By the end of this tutorial, you’ll have a vibrant piece of digital art. ### Starting with the Basics First, let's look at the overall structure of our code. We’ll define a grid with a specific number of rows and columns, add margins, and set colors. We'll then draw rectangles with varying border radii to create an interesting visual effect. ### Setting Up the Canvas We start by defining our grid dimensions, margins, and colors. Here are the variables we'll use: ```javascript let rows = 5; let cols = 5; let verticalMargin = 40; let horizontalMargin = 40; let borderRadius = 40; let cellWidth, cellHeight; let verticalPadding, horizontalPadding; let colors = ["#000000", "#5090ae", "#ed5731", "#f8a31e"]; ``` ### Defining the Setup Function In the `setup()` function, we create our canvas and calculate the dimensions of each cell in our grid. We also determine the padding within each cell: ```javascript function setup() { createCanvas(400, 400); cellWidth = (width - horizontalMargin) / cols; cellHeight = (height - verticalMargin) / rows; verticalPadding = cellHeight / 15; horizontalPadding = cellWidth / 15; noLoop(); } ``` Here, `createCanvas(400, 400)` sets up a 400x400 pixels canvas. The `cellWidth` and `cellHeight` are calculated by subtracting the margins from the total width and height, then dividing by the number of columns and rows, respectively. The padding values are a fraction of the cell dimensions, ensuring some space around the rectangles. ### Drawing the Rectangles The `draw()` function is where the magic happens. We set the background color, removed the stroke from shapes, and translated the origin point for easier drawing within the margins. We then use nested loops to draw the rectangles, applying different border radii based on the column index: ```javascript function draw() { background("#ece2c8"); noStroke(); translate(horizontalMargin / 2, verticalMargin / 2); for (let i = 0; i < rows; i++) { for (let j = 0; j < cols; j++) { fill(colors[(j + i) % colors.length]); let radius = getBorderRadius(j); rect( horizontalPadding / 2, verticalPadding / 2, cellWidth - horizontalPadding, cellHeight - verticalPadding, ...radius ); translate(cellWidth, 0); } translate(-cols * cellWidth, cellHeight); } } ``` ### Breaking Down the `draw()` Function - First, we set the background color and disabled the stroke, so we don't have an outline for the shapes. - `translate(horizontalMargin / 2, verticalMargin / 2);` Moves the origin point to account for the margins. Imagine the x-y axis like a graph where (0, 0) is the top-left corner. `translate(x, y)` moves the drawing tool to the coordinate (x, y) from the current origin. In this case, it shifts the origin to (20, 20), making it easier to draw within the margins. - The outer loop runs through each row, and the inner loop runs through each column. - `fill(colors[(j + i) % colors.length])` cycles through the color array. - The `await sleep(100)` introduces a delay between drawing each rectangle. - `let radius = getBorderRadius(j)` determines the corner radii based on the column index. - `rect()` draws the rectangle with the specified dimensions and border radii. - `translate(cellWidth, 0)` moves the drawing tool to the right by `cellWidth` pixels for the next column. - After completing a row, `translate(-cols * cellWidth, cellHeight)` resets the x position and moves down by `cellHeight` pixels to start the next row. ### Custom Functions We also define one helper function: `getBorderRadius`. ```javascript function getBorderRadius(colIndex) { switch(colIndex) { case 0: return [0, 0, 0, 0]; case 1: return [0, 0, 0, borderRadius]; case 2: return [0, borderRadius, 0, borderRadius]; case 3: return [borderRadius, borderRadius, 0, borderRadius]; case 4: return [borderRadius, borderRadius, borderRadius, borderRadius]; default: return [0, 0, 0, 0]; } } ``` - `getBorderRadius` returns different border radius configurations based on the column index. ### Conclusion Congratulations! You've now created a Bauhaus-inspired grid of rectangles with varying border radii. This exercise not only helps in understanding the basics of shapes and loops in p5.js but also adds a creative twist to your coding journey. ### Extra: Add Animation As a little extra, let's make this art more dynamic by drawing each shape individually with a delay between them, so we can see the process and better understand how the two nested loops work. To do this we will define a custom function, called `sleep` that pauses the execution for a specified duration, creating a visual delay effect. ```javascript function sleep(millisecondsDuration) { return new Promise((resolve) => { setTimeout(resolve, millisecondsDuration); }); } ``` Then, we have to add `async` in front of the `draw()` function definition so this becomes `async function draw()` and call the `sleep` function from inside the `draw` function. Add this call anywhere inside the nested loops, like this: ```javascript ... for (let i = 0; i < rows; i++) { for (let j = 0; j < cols; j++) { fill(colors[(j + i) % colors.length]); await sleep(100); let radius = getBorderRadius(j); ... ``` Now, run the code and you should get something like this ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/06/20240621-151627.gif) ### Experiment and Explore Feel free to experiment by: - Changing the number of rows and columns. - Adjusting the margins and border radius. - Adding more colors to the palette. The full code can be found here: [p5.js Web EditorA web editor for p5.js, a JavaScript library with the goal of making coding accessible to artists, designers, educators, and beginners.![](https://editor.p5js.org/favicon.ico)](https://editor.p5js.org/alex.codes.art/sketches/DbvSYlEr9?ref=alexcodesart.com) --- ### Wrapping up Thank you for following along with this tutorial! If you have any questions, feedback, or just want to share your creations, please feel free to leave a comment below. I’ll make sure to respond and help you out as best as I can. Stay connected for more exciting tutorials and creative coding tips by subscribing to this blog. I really appreciate it! Happy coding, and see you in the next tutorial! --- Want to stay updated with new articles? Just hit subscribe — it’s completely free, and I’d really appreciate the support. Thanks a lot! ## Sign up for Alex Codes Art Art with code for curious minds Subscribe Email sent! Check your inbox to complete your signup. No spam. Unsubscribe anytime. --- ### Next Tutorial In the next tutorial, we’ll dive into creating a more complex piece of art using additional p5.js functions and exploring more programming concepts. We will create our first dynamic digital art with code, in which we will learn about `noise`, `random` and many more concepts. [Creating Stylized Waves with p5.js: A Creative Coding TutorialHello and welcome to another exciting creative coding tutorial! Today, we will dive into the world of stylized waves using p5.js. This tutorial is perfect for beginners and seasoned coders alike. We’ll be exploring two powerful features of p5.js: noise and random. Thanks to these, every time![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/size/w256h256/2024/06/Logo--1-.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/06/Screenshot-2024-06-28-at-08.49.13.png)](https://alexcodesart.com/creating-stylized-waves-with-p5-js-a-creative-coding-tutorial/) ### Create Your First Digital Art with Code: A Step-by-Step Guide URL: https://alexcodesart.com/create-your-first-digital-artpiece-with-code-a-step-by-step-guide/ Last updated: 2025-07-01T14:19:33.000Z Let's build your first digital art with code. ### Starting with the Basics As a starting place to write and create your first digital art pieces, I recommend using the official [p5.js editor](https://editor.p5js.org/?ref=alexcodesart.com). Once you open the editor, you’ll see the code editor on the left side of the screen and the preview window on the right, which displays the results of running your code. We begin with the basic template of `setup()` and `draw()` functions. Here’s a quick reminder from our previous tutorial, which you can find here: [Getting Started with p5.js: An Introduction to Creative Coding for BeginnersIntroduction to Programming and p5.js Welcome to the world of creative coding with p5.js! Whether you’re an artist, designer, educator, or a complete beginner, p5.js is a powerful JavaScript library that makes coding visual and interactive projects accessible and fun. Let’s dive into the core concepts of![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/size/w256h256/2024/06/Logo--1-.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/06/grid0.jpg)](https://alexcodesart.com/getting-started-with-p5-js-an-introduction-to-creative-coding-for-beginners/) The `setup()` function is called once at the beginning of the program to set up initial environment properties such as screen size and background color. The `draw()` function, on the other hand, is called continuously, multiple times per second, to render the visual elements of your program on the screen. ```javascript function setup() { createCanvas(400, 500); } function draw() { background(220); } ``` ### **Breaking Down the Artwork: Key Elements** Upon closer inspection, we identify several key elements in this piece: 1. The background color. 2. Two overlapping semicircles, with the top one being slightly transparent. 3. An arch on top, made of eight separate curves. With this understanding, let’s create each element step-by-step. ### Setting the Background Color Moving forward, we will add all the described code inside the `draw()` function. First, we set the background color using the [background()](https://p5js.org/reference/?ref=alexcodesart.com#/p5/background) function. You can pass basic color names like 'red', 'blue', 'green', or a hex RGB notation like '#e8e0d5'. For our art, we use this hex color: ```javascript background('#e8e0d5'); ``` ### Drawing the Semicircles In p5.js, every shape has two properties defining its color: the stroke (the outline) and the fill. We don’t need any strokes, so we use the `noStroke()` function. To draw our first semicircle, we use these three lines of code: ```javascript noStroke(); fill('#9F6642'); arc(width / 2, height / 1.2, width / 2, width / 2, PI, TWO_PI); ``` The [fill()](https://p5js.org/reference/?ref=alexcodesart.com#/p5/fill) function works like the `background()` function, allowing you to pass the color you want to fill the shape with in various formats. The [arc()](https://p5js.org/reference/?ref=alexcodesart.com#/p5/arc) function draws an arc, taking several parameters: - The first two parameters are the arc center’s x and y coordinates (`width / 2` and `height / 1.2`). - The third and fourth parameters set the arc’s width and height (`width / 2` and `width / 2`). - The fifth and sixth parameters set the angles to draw the arc between (`PI` and `TWO_PI`), corresponding to 180 to 360 degrees in radians. ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/06/Screenshot_2024-05-28_at_09.58.48.png) One out of three elements done! If we run our code now, we will get this. That’s a start! ### Adding the Second Semicircle The second semicircle is drawn on top of the first one: ```javascript fill('#B39279B3'); arc(width / 2, height / 1.7, width / 2, width / 2, 0, PI); ``` Hexadecimal color is specified with `#RRGGBB`, where `RR`, `GG`, and `BB` are the values for red, green, and blue. To add transparency, add two additional digits (00 to FF) in front. Here, “B3” indicates approximately 70% opacity. - The position is set by `width / 2` and `height / 1.7`, slightly higher than the first semicircle. - The width and height are the same (`width / 2`). - The angles (`0` and `PI`) draw from 0 to 180 degrees. ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/06/Screenshot_2024-05-28_at_10.25.43.png) Two out of three elements done! Almost there! ### Creating the Arch First, let's add the variables that we need at the beginning of the file, on top of the `setup` function: ```javascript // Define spacing and dimensions for the lines and arches let lineGap = 10; let archGap = lineGap * 2; let archRadius = 60; let lineOffset = archRadius / 2; let archNumber = 8; ``` For the final element, the arch, we use a `for` loop to draw multiple segments, creating a smooth curve. We define the style and number of arches with `archNumber`. ```javascript // Define the style by setting the color and weight of the lines stroke('#264563'); strokeWeight(3); noFill(); // Ensure the arcs are not filled for (let i = 0; i < archNumber; i++) { line(width / 2 - (i * lineGap) - lineOffset, height / 1.75, width / 2 - (i * lineGap) - lineOffset, height / 3); line(width / 2 + (i * lineGap) + lineOffset, height / 1.75, width / 2 + (i * lineGap) + lineOffset, height / 3); } ``` The `line()` function accepts four parameters: the x and y coordinates for the start and end points. The first line draws the left segment, and the second line draws the right segment. For the arch, we use the `arc()` function: ```javascript arc(width / 2, height / 3, archRadius + i * archGap, archRadius + i * archGap, PI, TWO_PI); ``` Ensure the arc is not filled by calling `noFill()`. The final code looks like this: ```javascript stroke('#264563'); strokeWeight(3); noFill(); for (let i = 0; i < archNumber; i++) { line(width / 2 - (i * lineGap) - lineOffset, height / 1.75, width / 2 - (i * lineGap) - lineOffset, height / 3); line(width / 2 + (i * lineGap) + lineOffset, height / 1.75, width / 2 + (i * lineGap) + lineOffset, height / 3); arc(width / 2, height / 3, archRadius + i * archGap, archRadius + i * archGap, PI, TWO_PI); } ``` ![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/06/Screenshot_2024-05-31_at_15.41.22.png) YOUR first masterpiece! Congratulations! You have created your first piece of digital art with code! I am proud of you and you should be too! ### Your Turn to Experiment The full code together with the result can be found here: [p5.js Web EditorA web editor for p5.js, a JavaScript library with the goal of making coding accessible to artists, designers, educators, and beginners.![](https://editor.p5js.org/favicon.ico)](https://editor.p5js.org/alex.codes.art/sketches/kfs%5F1Bq51?ref=alexcodesart.com) An important part of learning is to experiment and play around. Familiarize yourself with the concepts we discovered today by: - Changing the color palette inside the `fill()`, `background()`, and `stroke()` functions. - Modifying variables defined at the beginning (`archNumber`, `lineGap`, `archRadius`). - Making any other changes you want. You’ll quickly see that you can create something unique from this example. --- Don’t miss any new posts — subscribe for free! It really helps me out, and I’d love to have you along. Thanks! ## Sign up for Alex Codes Art Art with code for curious minds Subscribe Email sent! Check your inbox to complete your signup. No spam. Unsubscribe anytime. ### Next Tutorial In the next tutorial, we’ll explore the `translate()`, `rect()`, and other programming concepts while creating this beautiful Bauhaus-inspired abstract art. [Vibrant Digital Art: Creating a Bauhaus-Inspired Grid of Colorful Shapes with CodeIn this tutorial, I’ll guide you through the process of creating a Bauhaus-inspired grid of colorful shapes using code. By the end of this tutorial, you’ll have a vibrant piece of digital art. Starting with the Basics First, let’s look at the overall structure of our code. We’ll![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/size/w256h256/2024/06/Logo--1-.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/size/w1200/2024/06/cover-7.png)](https://alexcodesart.com/creating-bauhaus-inspired-grid/) --- ### Wrapping up Thank you for following along with this tutorial! If you have any questions, feedback, or just want to share your own creations, please feel free to leave a comment below. I’ll make sure to respond and help you out as best as I can. Stay connected for more exciting tutorials and creative coding tips by subscribing to this blog. I really appreciate it! Happy coding, and see you in the next tutorial! ### Getting Started with p5.js: An Introduction to Creative Coding for Beginners URL: https://alexcodesart.com/getting-started-with-p5-js-an-introduction-to-creative-coding-for-beginners/ Last updated: 2025-07-01T14:17:06.000Z ### Introduction to Programming and p5.js Welcome to the world of creative coding with p5.js! Whether you're an artist, designer, educator, or a complete beginner, p5.js is a powerful JavaScript library that makes coding visual and interactive projects accessible and fun. Let's dive into the core concepts of p5.js, especially tailored for those new to programming. ### 1\. Setup and Draw Function - **`setup()`**: This function runs once when the program starts. It's used to set initial environment properties such as screen size and background color and to load media such as images and fonts. The setup function is like preparing your canvas. - `**draw()**`: Runs continuously after `setup()`, allowing the program to change over time. This function is called repeatedly and is used for animating or interacting with your project. Think of it as constantly drawing and redrawing to create animations or interactive pieces. ### 2\. Canvas - The canvas is the area where you draw your graphics, created with `createCanvas(width, height)`. It's the digital equivalent of a painter's canvas, setting the stage for your creative coding projects. ### 3\. Coordinates - In p5.js, the canvas is a grid where you can place your graphics. The coordinate system starts at the top-left corner (0, 0). The x-coordinate increases as you move right, and the y-coordinate increases as you move down. Understanding coordinates is essential for positioning shapes and creating interactive elements in your projects. ### 4\. Shapes - Basic functions like `rect(x, y, width, height)`, `ellipse(x, y, width, height)`, and `line(x1, y1, x2, y2)` allow you to draw shapes. These functions define the shapes' dimensions and positions on the canvas. Shapes are fundamental building blocks for your visual art. ### 5\. Color and Style - Functions such as `fill(r, g, b)`, `stroke(r, g, b)`, and `background(r, g, b)` control the colors of the shapes and the canvas background. Colors can be defined using RGB (red, green, blue) values. - `noFill()` and `noStroke()` functions are used to disable filling or stroking shapes, giving you more control over the appearance of your artwork. ### 6\. Interaction - Input functions like `mousePressed()` and variables such as `mouseX` and `mouseY` allow your sketches to interact with the user. You can make your sketches respond to mouse clicks, movements, or even keyboard actions, making your projects dynamic and engaging. ### 7\. Variables - Variables store data that can be used and manipulated by the program. They are helpful for storing the state of your sketch, such as the position of a shape or the color of a stroke. Variables are crucial for creating interactive and complex animations. ### 8\. Loops and Conditionals - **Loops** (`for` and `while`) allow you to repeat actions, which is particularly useful for creating patterns or animations. - **Conditionals** (`if`, `else if`, `else`) let you make decisions in your code, allowing for interactive and dynamic projects that respond differently under certain conditions. ### 9\. Libraries - p5.js supports various libraries that extend its capabilities, including p5.sound for audio, p5.play for game development, and more. These libraries allow you to incorporate complex features into your projects easily. ### 10\. Debugging - Console logs (`console.log()`) and error messages help you understand what your program is doing and identify any mistakes in your code. Effective debugging is key to smooth and efficient coding. ### 11\. Community and Resources - p5.js has a vast community and numerous resources for learning, including tutorials, examples, and forums. These resources are invaluable for beginners to get started and for experienced programmers to deepen their knowledge. p5.js emphasizes making coding and digital art accessible and enjoyable. By starting with these core concepts, you'll be well on your way to creating interactive and visually appealing projects. Don't hesitate to experiment and play around with the code – learning by doing is a great way to grasp the possibilities of p5.js. --- ## Next Steps Don’t miss any new posts — subscribe for free! It really helps me out, and I’d love to have you along. Thanks! ## Sign up for Alex Codes Art Art with code for curious minds Subscribe Email sent! Check your inbox to complete your signup. No spam. Unsubscribe anytime. After knowing the basics of p5.js, it is time to create your first digital art! Exciting! You can follow your first tutorial here, in which I will explain how to create your first digital art with code step by step. [Create Your First Digital Art with Code: A Step-by-Step GuideLet’s build your first digital art with code. Starting with the Basics As a starting place to write and create your first digital art pieces, I recommend using the official p5.js editor. Once you open the editor, you’ll see the code editor on the left side of the![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/size/w256h256/2024/06/Logo--1-.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/06/Screenshot_2024-05-31_at_15.41.22-1.png)](https://alexcodesart.com/create-your-first-digital-artpiece-with-code-a-step-by-step-guide/) ### Unleashing Your Imagination: An Introduction to Creative Coding and Generative Art with p5.js URL: https://alexcodesart.com/unleashing-your-imagination-an-introduction-to-creative-coding-and-generative-art-with-p5-js/ Last updated: 2025-07-01T14:18:16.000Z Welcome to the exciting world of creative coding! Whether you're a seasoned developer or a curious beginner, exploring the realms of generative art through p5.js opens up endless possibilities for artistic expression and computational creativity. In this blog post, we'll delve into the basics of p5.js, the essence of creative coding, and how you can get started with crafting mesmerizing generative art pieces. ### What is Creative Coding? Creative coding is a type of programming where the goal is to create something expressive rather than something functional. It's about using code as a medium for art and design. This approach merges the precision and logic of programming with the boundless creativity of art, resulting in unique and often unexpected outcomes. ### The Magic of Generative Art Generative art is a form of art that is algorithmically generated. It involves writing algorithms that follow certain rules to produce artwork that can range from structured patterns to organic, free-flowing designs. Each run of the algorithm can create a different result, making generative art a perfect blend of consistency and unpredictability. ### Enter p5.js: Your Toolkit for Creative Coding p5.js is a JavaScript library designed to make coding accessible for artists, designers, educators, and beginners. Developed by Lauren McCarthy and the Processing Foundation, p5.js simplifies the process of creating visuals and interactive content on the web. Here’s why p5.js is the perfect tool for your creative coding journey: - **Easy to Learn**: p5.js uses JavaScript, a widely-used language, making it accessible to many. - **Rich Functionality**: It offers a wide range of built-in functions for drawing, animation, and interaction. - **Interactive**: p5.js sketches can be embedded directly into websites, making it easy to share your creations. - **Community Support**: With a large and active community, you can find plenty of resources, examples, and forums to help you along the way. ### Getting Started with p5.js Let's dive into a simple example to see p5.js in action. Below is a basic setup to create a canvas and draw a moving circle: 1. **Setting Up**: First, make sure you have a code editor (like VS Code) and a browser. 2. **HTML Structure**: Create a new HTML file and include the p5.js library. ```html p5.js Intro ``` 1. **Sketch.js File**: Create a file named `sketch.js` and add the following code: ```javascript function setup() { createCanvas(400, 400); } function draw() { background(220); ellipse(mouseX, mouseY, 50, 50); } ``` In this simple sketch, `setup()` is a p5.js function that runs once when the program starts, setting up the canvas size. The `draw()` function runs continuously, refreshing the canvas and drawing an ellipse that follows the mouse cursor. ### Expanding Your Creativity With p5.js, the only limit is your imagination. Here are a few ideas to expand your generative art projects: - **Dynamic Patterns**: Create patterns that change over time or in response to user inputs. - **Interactive Art**: Use mouse and keyboard events to make your art interactive. - **Data-Driven Art**: Incorporate data from external sources (like APIs) to influence your artwork. ### Resources to Explore - [**p5.js Website**](https://p5js.org/?ref=alexcodesart.com): The official website offers extensive documentation and examples. - [**p5.js Editor**](https://editor.p5js.org/?ref=alexcodesart.com): The official editor in which you can easily create and visualize p5.js sketches - [**Coding Train**](https://www.youtube.com/user/shiffman?ref=alexcodesart.com): Daniel Shiffman’s YouTube channel is a treasure trove of tutorials on p5.js and creative coding. - [**OpenProcessing**](https://www.openprocessing.org/?ref=alexcodesart.com): A community platform to share and explore p5.js sketches. ### Conclusion Embarking on a journey with p5.js opens up a world of creative coding and generative art. By merging the precision of coding with the freedom of artistic expression, you can create stunning, interactive art pieces that evolve and surprise. So grab your code editor, fire up p5.js, and start bringing your artistic visions to life! Don’t miss any new posts — subscribe for free! It really helps me out, and I’d love to have you along. Thanks! Happy coding! ## Sign up for Alex Codes Art Art with code for curious minds Subscribe Email sent! Check your inbox to complete your signup. No spam. Unsubscribe anytime. ### Next Steps In the next article, we are looking at some basic p5.js concepts together with some basic programming concepts. See you in the next one! [Getting Started with p5.js: An Introduction to Creative Coding for BeginnersIntroduction to Programming and p5.js Welcome to the world of creative coding with p5.js! Whether you’re an artist, designer, educator, or a complete beginner, p5.js is a powerful JavaScript library that makes coding visual and interactive projects accessible and fun. Let’s dive into the core concepts of![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/size/w256h256/2024/06/Logo--1-.png)Alex Codes ArtAlex Postolache![](https://storage.ghost.io/c/02/0d/020db2da-24e8-4541-a343-67633f75baaf/content/images/2024/06/grid0.jpg)](https://alexcodesart.com/getting-started-with-p5-js-an-introduction-to-creative-coding-for-beginners/)