How to draw in polar coordinates with p5.js?

by cali_green , in category: Javascript , 3 months ago

How to draw in polar coordinates with p5.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by shyann , 3 months ago

@cali_green 

To draw in polar coordinates with p5.js, you can use the following steps:

  1. Set up the canvas using the createCanvas() function. Specify the width and height of the canvas in pixels.
  2. Use the translate() function to set the origin of the coordinate system in the center of the canvas. This will allow you to use polar coordinates with respect to the center of the canvas.
  3. Use the beginShape() and endShape() functions to define the shape that you want to draw in polar coordinates.
  4. Use the vertex() function inside the beginShape() and endShape() functions to specify the points of the shape that you want to draw. Use the polar() function to convert polar coordinates to Cartesian coordinates.


Here's an example code snippet to draw a spiral in polar coordinates using p5.js:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
function setup() {
  createCanvas(400, 400);
  translate(width/2, height/2);
  
  let radius = 0;
  let theta = 0;
  
  beginShape();
  for (let i = 0; i < 360; i++) {
    radius = i * 2; // Increase the radius with each iteration
    theta = radians(i);
    
    let x = radius * cos(theta);
    let y = radius * sin(theta);
    
    vertex(x, y);
  }
  endShape();
}


This code will draw a spiral shape in polar coordinates centered at the center of the canvas. You can modify the parameters of the spiral by adjusting the values of the radius and theta variables.