Coloring the Borders of Shapes in p5.js
Note: this page has been created with the use of AI. Please take caution, and note that the content of this page does not necessarily reflect the opinion of Cratecode.
Are you ready to add some color to your coding life? Then let's get started! With the stroke() function in p5.js, a JavaScript library, we can paint the town red... or any color you like!
The Basics
In p5.js, shapes are drawn with a border, or "stroke", by default. This stroke is black unless we tell it otherwise. And how do we tell it otherwise? You guessed it - with the stroke() function.
function setup() { createCanvas(400, 400); background("white"); } function draw() { stroke("red"); rect(100, 100, 200, 200); }
In this example, we've created a square with a red border.
The stroke() Function
The stroke() function takes either three arguments (for RGB values) or one argument (for grayscale or color names). If you're feeling like a grayscale kind of day:
function draw() { stroke(50); rect(100, 100, 200, 200); }
This will draw a square with a gray border.
If you're feeling a bit more colorful, you can use RGB values:
function draw() { stroke(255, 0, 0); rect(100, 100, 200, 200); }
This will draw a square with a bright red border. The RGB values can be between 0 and 255.
No Stroke?
What if you don't want a border at all? No problem! The noStroke() function has you covered.
function draw() { noStroke(); rect(100, 100, 200, 200); }
This gives us a borderless square.
And there you have it! With the stroke() function in p5.js, you've got the power to bring color to your code. So go ahead and paint the town red... or blue, or green, or whatever color your heart desires!
Hey there! Want to learn more? Cratecode is an online learning platform that lets you forge your own path. Click here to check out a lesson: Drawing Basic Shapes (psst, it's free!).
FAQ
How do I change the color of a shape's border in p5.js?
You can use the stroke() function to change the color of a shape's border. You can pass in either one argument for grayscale or color names, or three arguments for RGB values.
What does the stroke() function do in p5.js?
The stroke() function in p5.js sets the color used to draw lines and borders around shapes.
How can I draw a shape without a border in p5.js?
You can use the noStroke() function in p5.js to draw shapes without a border.
Can I use color names with the stroke() function in p5.js?
Yes, you can use color names with the stroke() function in p5.js. For example, stroke("red") will create a red border.
What are RGB values in the context of the stroke() function in p5.js?
RGB values are a way to represent color by indicating the intensity of red (R), green (G), and blue (B) light. In the context of the stroke() function in p5.js, you can pass in three arguments to represent RGB values, each ranging from 0 to 255.