Anna Mei
Anna Mei

Reputation: 137

How to create roundish shapes in p5.js?

I am trying to code a zen garden as a semester project. I work with the p5.js JavaScript library and my question is how to create roundish shapes. I want to use those shapes as stones in the garden.

Here is my code for one stone.:

const x = 100;
const y = 100;

function setup() {
  createCanvas(400, 400);
}

function draw() {
  
  fill('green');
  beginShape();
  curveVertex(x+51,y+20);
  curveVertex(x+65,y+23);
  curveVertex(x+77,y+23);
  curveVertex(x+83,y+34);
  curveVertex(x+88,y+45);
  curveVertex(x+90,y+59);
  curveVertex(x+75,y+61);
  curveVertex(x+65,y+70);
  curveVertex(x+52,y+69);
  curveVertex(x+40,y+59);
  curveVertex(x+45,y+44);
  curveVertex(x+41,y+30);
  endShape(CLOSE);
  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.min.js"></script>

The problem is that the last curve does not look roundish, but closes kind of abruptly.

Has anyone a better idea how I could generate roundish stones for my garden in different sizes?

Of course any other helpful input is welcome.

enter image description here

Upvotes: 2

Views: 437

Answers (1)

George Profenza
George Profenza

Reputation: 51837

You're definitely on the right track. There's one detail you're accidentally missing out: you're using draw() without clearing, using background(255).

Here's your code slown down: notice how each frame the outlines get sharper

const x = 100;
const y = 100;

function setup() {
  createCanvas(400, 400);
  frameRate(3);
}

function draw() {
  
  scale(2);
  fill('green');
  beginShape();
  curveVertex(x+51,y+20);
  curveVertex(x+65,y+23);
  curveVertex(x+77,y+23);
  curveVertex(x+83,y+34);
  curveVertex(x+88,y+45);
  curveVertex(x+90,y+59);
  curveVertex(x+75,y+61);
  curveVertex(x+65,y+70);
  curveVertex(x+52,y+69);
  curveVertex(x+40,y+59);
  curveVertex(x+45,y+44);
  curveVertex(x+41,y+30);
  endShape(CLOSE);
  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.min.js"></script>

And here's the difference when clearing the frame:

const x = 100;
const y = 100;

function setup() {
  createCanvas(400, 400);
  // smooth();
}

function draw() {
  background(255);
  scale(2);
  fill('green');
  beginShape();
  curveVertex(x+51,y+20);
  curveVertex(x+65,y+23);
  curveVertex(x+77,y+23);
  curveVertex(x+83,y+34);
  curveVertex(x+88,y+45);
  curveVertex(x+90,y+59);
  curveVertex(x+75,y+61);
  curveVertex(x+65,y+70);
  curveVertex(x+52,y+69);
  curveVertex(x+40,y+59);
  curveVertex(x+45,y+44);
  curveVertex(x+41,y+30);
  endShape(CLOSE); 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.min.js"></script>

(Optionally, smooth() can help a bit, but in this case it doesn't seem to make a huge difference).

Nice idea and sketches! Good luck with your project!

Upvotes: 3

Related Questions