Skip to content

Instantly share code, notes, and snippets.

@WilliamLivingood
Created September 24, 2025 05:51
Show Gist options
  • Select an option

  • Save WilliamLivingood/f0702472e0b0747350ec1c3e6b806d15 to your computer and use it in GitHub Desktop.

Select an option

Save WilliamLivingood/f0702472e0b0747350ec1c3e6b806d15 to your computer and use it in GitHub Desktop.
Processing Code to Draw a Snowflake
import processing.svg.*;
// paramater
final int canvas_size = 1000;
final String out_file = "snowflake.svg";
final int num_sides = 10;
final float outer_radius = 350;
final float hub_radius = 40;
final float arm_length = 260;
final int arm_steps = 10;
final float branch_angle = radians(35);
final float branch_scale = 0.20;
final float stroke_width = 1.0;
void settings() {
size(canvas_size, canvas_size);
}
void setup() {
beginRecord(SVG, out_file);
background(255);
stroke(0);
strokeWeight(stroke_width);
noFill();
noLoop();
draw_polygon(num_sides, outer_radius);
draw_polygon(num_sides, hub_radius);
draw_snowflake();
endRecord();
}
//geometry stuff
PVector pt_polar(float cx, float cy, float r, float ang) {
return new PVector(cx + r * cos(ang), cy + r * sin(ang));
}
void draw_segment(PVector a, PVector b) {
line(a.x, a.y, b.x, b.y);
}
void draw_polygon(int n, float r) {
float cx = width * 0.5, cy = height * 0.5;
float a0 = -HALF_PI, da = TWO_PI / n;
PVector first = null, prev = null;
for (int i = 0; i < n; i++) {
PVector p = pt_polar(cx, cy, r, a0 + i * da);
if (i == 0) first = p;
if (prev != null) draw_segment(prev, p);
prev = p;
}
draw_segment(prev, first);
}
void draw_snowflake() {
float cx = width * 0.5, cy = height * 0.5;
float a0 = -HALF_PI;
float da = TWO_PI / num_sides;
for (int i = 0; i < num_sides; i++) {
float ang = a0 + i * da;
draw_arm(cx, cy, ang);
}
}
void draw_arm(float cx, float cy, float ang) {
// main arm
float step_len = arm_length / arm_steps;
PVector p = pt_polar(cx, cy, hub_radius, ang);
for (int s = 0; s < arm_steps; s++) {
PVector q = pt_polar(p.x, p.y, step_len, ang);
draw_segment(p, q);
float t = (arm_steps == 1) ? 0 : (1f - s / float(arm_steps - 1));
float branch_len = arm_length * branch_scale * t;
// branches left/right
if (branch_len > 0) {
PVector bl = pt_polar(q.x, q.y, branch_len, ang - branch_angle);
PVector br = pt_polar(q.x, q.y, branch_len, ang + branch_angle);
draw_segment(q, bl);
draw_segment(q, br);
}
p = q;
}
// small fork at the tip
float tip = arm_length * 0.08;
PVector tip_l = pt_polar(p.x, p.y, tip, ang - radians(20));
PVector tip_r = pt_polar(p.x, p.y, tip, ang + radians(20));
draw_segment(p, tip_l);
draw_segment(p, tip_r);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment