Grid tools
Working with coordinates in p5.js
Source Code for this Sketch
function setup() {
createCanvas(500, 600, P2D, canvas)
colorMode(HSL)
}
function roundedTriangle(x1, y1, x2, y2, x3, y3, r, color) {
fill(color)
strokeWeight(0)
// It would be preferable to have the rounded
// triangle fit _inside_ the specified points.
// This is simple-ish for right triangles but
// somewhat complicated for others.
//
// Each corner needs to be "pulled" toward the
// center of the triangle by some amount.
//
// It's also possible for r to be too large,
// which causes the triangle to disappear.
triangle(x1, y1, x2, y2, x3, y3)
stroke(color)
strokeWeight(r * 2)
line(x1, y1, x2, y2)
line(x2, y2, x3, y3)
line(x1, y1, x3, y3)
}
function roundedSquare(x, y, w, h, r, color) {
fill(color)
strokeWeight(0)
strokeCap(ROUND)
if (w-r*2 > 0 && h-r*2 > 0) {
rect(x+r, y+r, w-r*2, h-r*2)
}
stroke(color)
strokeWeight(r * 2)
line(x+r, y+r, x+r, y+h-r)
line(x+r, y+r, x+w-r, y+r)
line(x+w-r, y+r, x+w-r, y+h-r)
line(x+r, y+h-r, x+w-r, y+h-r)
}
function grid(spacing, color, numbering) {
if (typeof numbering === "undefined") {
numbering = false
}
fill(color)
stroke(color)
strokeWeight(1)
textSize(9)
if (numbering) {
text("0", 5, 10)
}
for (let i = spacing; i < width; i += spacing) {
if (numbering) {
text(i, i + 5, 10)
}
line(i, 0, i, height);
}
for (let i = spacing; i < height; i += spacing) {
if (numbering) {
text(i, 5, i + 10)
}
line(0, i, width, i);
}
}
function showMousePosition() {
strokeWeight(0)
stroke(0)
fill(0)
text("(" + round(mouseX) + ", " + round(mouseY) + ")", mouseX, mouseY + 30)
}
function draw() {
background(45, 40, 85)
grid(50, color(45, 30, 65), true)
fill(214, 100, 50)
circle(175, 375, 250)
roundedTriangle(200, 200, 250, 450, 400, 400, 10, color(45, 100, 50))
roundedSquare(250, 100, 200, 200, 50, color(330, 100, 50))
showMousePosition()
}
You may use all or part of the p5 code seen on this page for your own creations, without restriction. Attribution is appreciated but not required.
This sketch also includes the following sources: p5common.js . Sources are available under their respective licenses.