Project 07: Butterfly Curve

sketchDownload

var n = 100; //Number of points
var r = 50; //Radius

var x = [] //List of X values
var y = [] //List of Y values
var t = [] //Parameter 


function setup() 
{
	createCanvas(480, 480);
	frameRate(60)
	//Initialize Butterfly curve by assigning X, Y and T values
    for (let i = 0; i < n; i++) {
        t[i] = random(0, 180);
        //Equations taken from https://mathworld.wolfram.com/ButterflyCurve.html
        x[i] = r * sin(t[i]) * (exp(cos(t[i])) - 3 * cos(4 * t[i]) - pow(sin(t[i] / 10), 5));
        y[i] = r * cos(t[i]) * (exp(cos(t[i])) - 3 * cos(4 * t[i]) - pow(sin(t[i] / 10), 5));
    }
}


function draw() 
{

    background(0);
    //Make (0,0) center of canvas
    translate(width / 2, height / 2);


    let my = map(mouseY,0,height,18*PI,6*PI); //Map mouse Y to number of rotation iterations of butterflies
    push();
   	noFill();
    stroke(100)
    strokeWeight(0.25)

    //Begin curve for butterfly
    beginShape();
    for (let i = 0; i < my; i += 0.01)
    {
    	//Equations taken from https://mathworld.wolfram.com/ButterflyCurve.html
      	let bx = r * sin(i) * (exp(cos(i)) - 3 * cos(4 * i) - pow(sin(i / 10), 5));
      	let by = r * cos(i) * (exp(cos(i)) - 3 * cos(4 * i) - pow(sin(i / 10), 5));
      	//Vertex has X and Y points corresponding to parametric equations
      	vertex(bx,by)
    }
    endShape();
    pop();

    //Draw flying circles
    push();
    fill(255);
    noStroke();
    //Loop for number of circles
    for (let i = 0; i < n; i++) 
    {
    	let mx = map(mouseX,0,width,-0.005,0.005); //Map mouse X to speed at which parameter changes (from negative to positive speeds)
        t[i] += mx; //Add mapped mouse X to parameter

        //Reset parameter if it exceeds 180 degrees
        if (t[i] > 180)
        {
        	t[i] = 0;
        }

        //Equations taken from https://mathworld.wolfram.com/ButterflyCurve.html
        x[i] = r * sin(t[i]) * (exp(cos(t[i])) - 3 * cos(4 * t[i]) - pow(sin(t[i] / 10), 5));
        y[i] = r * cos(t[i]) * (exp(cos(t[i])) - 3 * cos(4 * t[i]) - pow(sin(t[i] / 10), 5));

        //Draw circle
        circle(x[i], y[i], 3);
    }
    pop();
}

The Butterfly curve seemed really similar to the Lorentz attractor curves I was looking for last week’s Looking Outwards. I initially wanted to make a circle follow the trail of the curve and have the mouseX determine the speed, however I realized that it was actually easier to have multiple circles follow the path.

MouseX controls speed and direction of circles, MouseY controls amount of curve iterations of the butterfly curve.

Leave a Reply