Metaballs in Processing as vector

2019-08-27 14:12发布

问题:

i am trying to create a kind of metaball, nice curves between two circles.

Something like the image, the lines are drawn straight but can also be more curved. I need them as a vector in Processing. Does anyone can help me? thanks in advance!

Example in paperjs: http://paperjs.org/examples/meta-balls/

image: http://www.smeulders.biz/tmp/metaballs.png

void setup() {
  size(500,500);
  ellipse(100, 250, 100, 100);
  ellipse(350, 250, 200, 200);
}
void draw() {}

回答1:

With a bit of math (to workout distance between circles) and a bit of pixel manipulation to set pixel colours based on these calculated distances, you can render 2D metaballs and there plenty of examples

For fun however I decided to take a stab at making a very hacky version of the example you shared by simply rendering ellipses into an image, then filtering the image at the end:

PGraphics pg;//a separate layer to render into
int dilateAmt = 3;
PImage grid;//pixels of the grid alone, minus the 'cursor'

void setup(){
  size(400,400);
  //create a new layer
  pg = createGraphics(width,height);  
  pg.beginDraw();
  //draw a di-grid inside
  pg.background(255);
  pg.noStroke();pg.fill(0);
  for(int y = 0 ; y < 5; y++)
    for(int x = 0 ; x < 5; x++)
      pg.ellipse((y%2==0?40:0)+(x * 80),40+(y * 80), 40, 40);
  pg.endDraw();
  //grab a snapshot for later re-use
  grid = pg.get();
}
void draw(){
  pg.beginDraw();
  //draw the cached grid (no need to loop and re-render circles) 
  pg.image(grid,0,0);
  //and the cursor into the layer
  pg.ellipse(mouseX,mouseY,60,60);
  pg.endDraw();
  //since PGraphics extends PImage, you can filter, so we dilate
  for(int i = 0; i < dilateAmt; i++) pg.filter(DILATE);
  //finally render the result
  image(pg,0,0);
}
void keyPressed(){
  if(keyCode == UP) dilateAmt++;
  if(keyCode == DOWN) dilateAmt--;
  if(dilateAmt < 1) dilateAmt = 1;
  println(dilateAmt);
}

Note that the end result is raster, not vector.

If you want to achieve the exact effect you will need to port your example from JavaScript to Java. The source code is available.

If you like Processing the above example you could use plain javascript using p5.js. You'll find most of the familiar functions from Processing, but also directly use the paper.js library.